repo.py 11.2 KB
Newer Older
Markus Scheidgen's avatar
Markus Scheidgen committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Copyright 2018 Markus Scheidgen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an"AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
The repository API of the nomad@FAIRDI APIs. Currently allows to resolve repository
meta-data.
"""

from flask_restplus import Resource, abort, fields
21
22
from flask import request, g
from elasticsearch_dsl import Q
23
from elasticsearch.exceptions import NotFoundError
Markus Scheidgen's avatar
Markus Scheidgen committed
24
import datetime
Markus Scheidgen's avatar
Markus Scheidgen committed
25

Markus Scheidgen's avatar
Markus Scheidgen committed
26
from nomad import search
Markus Scheidgen's avatar
Markus Scheidgen committed
27

Markus Scheidgen's avatar
Markus Scheidgen committed
28
from .app import api, rfc3339DateTime
29
from .auth import login_if_available
Markus Scheidgen's avatar
Markus Scheidgen committed
30
31
from .common import pagination_model, pagination_request_parser, calc_route

32
ns = api.namespace('repo', description='Access repository metadata.')
Markus Scheidgen's avatar
Markus Scheidgen committed
33
34
35
36
37


@calc_route(ns)
class RepoCalcResource(Resource):
    @api.response(404, 'The upload or calculation does not exist')
38
    @api.response(401, 'Not authorized to access the calculation')
39
    @api.response(200, 'Metadata send', fields.Raw)
40
    @api.doc('get_repo_calc')
41
    @login_if_available
42
    def get(self, upload_id, calc_id):
Markus Scheidgen's avatar
Markus Scheidgen committed
43
44
45
        """
        Get calculation metadata in repository form.

46
        Repository metadata only entails the quantities shown in the repository.
47
        Calcs are references via *upload_id*, *calc_id* pairs.
Markus Scheidgen's avatar
Markus Scheidgen committed
48
49
        """
        try:
50
51
52
53
54
55
56
57
58
59
60
            calc = search.Entry.get(calc_id)
        except NotFoundError:
            abort(404, message='There is no calculation %s/%s' % (upload_id, calc_id))

        if calc.with_embargo or not calc.published:
            if g.user is None:
                abort(401, message='Not logged in to access %s/%s.' % (upload_id, calc_id))

            is_owner = g.user.user_id == 0
            if not is_owner:
                for owner in calc.owners:
61
62
63
                    # At somepoint ids will be emails (strings) anyways.
                    # Right now it is hard to make sure that both are either str or int.
                    if str(owner.user_id) == str(g.user.user_id):
64
65
66
67
68
69
                        is_owner = True
                        break
            if not is_owner:
                abort(401, message='Not authorized to access %s/%s.' % (upload_id, calc_id))

        return calc.to_dict(), 200
Markus Scheidgen's avatar
Markus Scheidgen committed
70
71
72


repo_calcs_model = api.model('RepoCalculations', {
73
74
75
76
77
    'pagination': fields.Nested(pagination_model, allow_null=True),
    'scroll': fields.Nested(allow_null=True, skip_none=True, model=api.model('Scroll', {
        'total': fields.Integer(description='The total amount of hits for the search.'),
        'scroll_id': fields.String(allow_null=True, description='The scroll_id that can be used to retrieve the next page.'),
        'size': fields.Integer(help='The size of the returned scroll page.')})),
78
79
80
    'results': fields.List(fields.Raw, description=(
        'A list of search results. Each result is a dict with quantitie names as key and '
        'values as values')),
81
    'quantities': fields.Raw(description=(
Markus Scheidgen's avatar
Markus Scheidgen committed
82
        'A dict with all aggregations. Each aggregation is dictionary with a metrics dict as '
83
84
        'value and quantity value as key. The metrics are code runs(calcs), %s. '
        'There is a pseudo quantity "total" with a single value "all" that contains the metrics over all results. ' %
85
        ', '.join(search.metrics_names)))
Markus Scheidgen's avatar
Markus Scheidgen committed
86
87
88
89
90
})

repo_request_parser = pagination_request_parser.copy()
repo_request_parser.add_argument(
    'owner', type=str,
91
    help='Specify which calcs to return: ``all``, ``public``, ``user``, ``staging``, default is ``all``')
Markus Scheidgen's avatar
Markus Scheidgen committed
92
93
94
95
96
97
repo_request_parser.add_argument(
    'from_time', type=lambda x: rfc3339DateTime.parse(x),
    help='A yyyy-MM-ddTHH:mm:ss (RFC3339) minimum entry time (e.g. upload time)')
repo_request_parser.add_argument(
    'until_time', type=lambda x: rfc3339DateTime.parse(x),
    help='A yyyy-MM-ddTHH:mm:ss (RFC3339) maximum entry time (e.g. upload time)')
98
99
100
101
repo_request_parser.add_argument(
    'scroll', type=bool, help='Enable scrolling')
repo_request_parser.add_argument(
    'scroll_id', type=str, help='The id of the current scrolling window to use.')
Markus Scheidgen's avatar
Markus Scheidgen committed
102
repo_request_parser.add_argument(
103
104
    'metrics', type=str, help=(
        'Metrics to aggregate over all quantities and their values as comma separated list. '
105
        'Possible values are %s.' % ', '.join(search.metrics_names)))
Markus Scheidgen's avatar
Markus Scheidgen committed
106

107
108
109
110
for search_quantity in search.search_quantities.keys():
    _, _, description = search.search_quantities[search_quantity]
    repo_request_parser.add_argument(search_quantity, type=str, help=description)

Markus Scheidgen's avatar
Markus Scheidgen committed
111
112
113

@ns.route('/')
class RepoCalcsResource(Resource):
114
    @api.doc('search')
115
    @api.response(400, 'Invalid requests, e.g. wrong owner type or bad quantities')
Markus Scheidgen's avatar
Markus Scheidgen committed
116
117
118
119
120
    @api.expect(repo_request_parser, validate=True)
    @api.marshal_with(repo_calcs_model, skip_none=True, code=200, description='Metadata send')
    @login_if_available
    def get(self):
        """
121
122
123
        Search for calculations in the repository from, paginated.

        The ``owner`` parameter determines the overall entries to search through.
124
125
126
127
        Possible values are: ``all`` (show all entries visible to the current user), ``public``
        (show all publically visible entries), ``user`` (show all user entries, requires login),
        ``staging`` (show all user entries in staging area, requires login).

128
129
130
131
132
        You can use the various quantities to search/filter for. For some of the
        indexed quantities this endpoint returns aggregation information. This means
        you will be given a list of all possible values and the number of entries
        that have the certain value. You can also use these aggregations on an empty
        search to determine the possible values.
133
134
135

        The pagination parameters allows determine which page to return via the
        ``page`` and ``per_page`` parameters. Pagination however, is limited to the first
Markus Scheidgen's avatar
Markus Scheidgen committed
136
137
138
139
140
141
142
143
        100k (depending on ES configuration) hits.

        An alternative to pagination is to use ``scroll`` and ``scroll_id``. With ``scroll``
        you will get a ``scroll_id`` on the first request. Each call with ``scroll`` and
        the respective ``scroll_id`` will return the next ``per_page`` (here the default is 1000)
        results. Scroll however, ignores ordering and does not return aggregations.
        The scroll view used in the background will stay alive for 1 minute between requests.
        If the given ``scroll_id`` is not available anymore, a HTTP 400 is raised.
144
145
146
147
148

        The search will return aggregations on a predefined set of quantities. Aggregations
        will tell you what quantity values exist and how many entries match those values.

        Ordering is determined by ``order_by`` and ``order`` parameters.
149
        """
150
151

        try:
152
153
            scroll = bool(request.args.get('scroll', False))
            scroll_id = request.args.get('scroll_id', None)
154
            page = int(request.args.get('page', 1))
155
            per_page = int(request.args.get('per_page', 10 if not scroll else 1000))
156
            order = int(request.args.get('order', -1))
157
            metrics_str = request.args.get('metrics', '')
Markus Scheidgen's avatar
Markus Scheidgen committed
158

Markus Scheidgen's avatar
Markus Scheidgen committed
159
160
161
162
163
            from_time = rfc3339DateTime.parse(request.args.get('from_time', '2000-01-01'))
            until_time_str = request.args.get('until_time', None)
            until_time = rfc3339DateTime.parse(until_time_str) if until_time_str is not None else datetime.datetime.now()
            time_range = (from_time, until_time)

164
165
            metrics = [
                metric for metric in metrics_str.split(',')
166
                if metric in search.metrics_names]
167
168
169
        except Exception:
            abort(400, message='bad parameter types')

170
        owner = request.args.get('owner', 'all')
171
        order_by = request.args.get('order_by', 'formula')
172
173

        try:
174
            assert page >= 1
175
176
177
178
            assert per_page > 0
        except AssertionError:
            abort(400, message='invalid pagination')

179
180
181
        if order not in [-1, 1]:
            abort(400, message='invalid pagination')

182
183
184
185
186
187
188
        # TODO this should be removed after migration
        # if owner == 'migrated':
        #     q = Q('term', published=True) & Q('term', with_embargo=False)
        #     if g.user is not None:
        #         q = q | Q('term', owners__user_id=g.user.user_id)
        #     q = q & ~Q('term', **{'uploader.user_id': 1})  # pylint: disable=invalid-unary-operand-type
        if owner == 'all':
189
190
191
            q = Q('term', published=True) & Q('term', with_embargo=False)
            if g.user is not None:
                q = q | Q('term', owners__user_id=g.user.user_id)
192
193
        elif owner == 'public':
            q = Q('term', published=True) & Q('term', with_embargo=False)
194
195
196
197
        elif owner == 'user':
            if g.user is None:
                abort(401, message='Authentication required for owner value user.')

198
            q = Q('term', owners__user_id=g.user.user_id)
199
200
201
        elif owner == 'staging':
            if g.user is None:
                abort(401, message='Authentication required for owner value user.')
202
            q = Q('term', published=False) & Q('term', owners__user_id=g.user.user_id)
203
204
205
206
        elif owner == 'admin':
            if g.user is None or not g.user.is_admin:
                abort(401, message='This can only be used by the admin user.')
            q = None
207
208
209
        else:
            abort(400, message='Invalid owner value. Valid values are all|user|staging, default is all')

210
211
212
        # TODO this should be removed after migration
        without_currupted_mainfile = ~Q('term', code_name='currupted mainfile')  # pylint: disable=invalid-unary-operand-type
        q = q & without_currupted_mainfile if q is not None else without_currupted_mainfile
Markus Scheidgen's avatar
Markus Scheidgen committed
213

214
215
216
217
218
219
220
221
222
223
224
        search_parameters = dict(**request.args)
        search_parameters.pop('owner', None)
        search_parameters.pop('scroll', None)
        search_parameters.pop('scroll_id', None)
        search_parameters.pop('per_page', None)
        search_parameters.pop('page', None)
        search_parameters.pop('order', None)
        search_parameters.pop('order_by', None)
        search_parameters.pop('metrics', None)
        search_parameters.pop('from_time', None)
        search_parameters.pop('until_time', None)
225
226

        try:
227
            if scroll:
228
229
230
                results = search.scroll_search(
                    q=q, scroll_id=scroll_id, size=per_page, search_parameters=search_parameters)

231
            else:
232
233
234
235
236
237
238
239
240
241
                results = search.metrics_search(
                    q=q, per_page=per_page, page=page, order=order, order_by=order_by,
                    time_range=time_range, metrics_to_use=metrics, search_parameters=search_parameters)

                # TODO just a work around to make things prettier
                quantities = results['quantities']
                if 'code_name' in quantities and 'currupted mainfile' in quantities['code_name']:
                    del(quantities['code_name']['currupted mainfile'])

            return results, 200
Markus Scheidgen's avatar
Markus Scheidgen committed
242
243
        except search.ScrollIdNotFound:
            abort(400, 'The given scroll_id does not exist.')
244
245
        except KeyError as e:
            abort(400, str(e))