archive.py 6.99 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 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.

15
16
17
18
19
"""
The archive API of the nomad@FAIRDI APIs. This API is about serving processed
(parsed and normalized) calculation data in nomad's *meta-info* format.
"""

20
from typing import Dict, Any
21
22
import os.path
from flask import send_file
23
from flask_restplus import abort, Resource
24
import json
25
import importlib
26

27
28
import nomad_meta_info

29
from nomad.files import UploadFiles, Restricted
30

31
from .auth import authenticate, create_authorization_predicate
Markus Scheidgen's avatar
Markus Scheidgen committed
32
from .api import api
33
34
35
from .common import calc_route

ns = api.namespace(
36
37
    'archive',
    description='Access archive data and archive processing logs.')
38
39
40
41


@calc_route(ns, '/logs')
class ArchiveCalcLogResource(Resource):
42
    @api.doc('get_archive_logs')
43
    @api.response(404, 'The upload or calculation does not exist')
44
    @api.response(401, 'Not authorized to access the data.')
45
    @api.response(200, 'Archive data send', headers={'Content-Type': 'application/plain'})
46
    @authenticate(signature_token=True)
47
    def get(self, upload_id, calc_id):
48
49
50
        """
        Get calculation processing log.

51
        Calcs are references via *upload_id*, *calc_id* pairs.
52
        """
53
        archive_id = '%s/%s' % (upload_id, calc_id)
54

55
        upload_files = UploadFiles.get(
56
            upload_id, is_authorized=create_authorization_predicate(upload_id, calc_id))
57

58
        if upload_files is None:
59
            abort(404, message='Upload %s does not exist.' % upload_id)
60
61
62

        try:
            return send_file(
63
                upload_files.archive_log_file(calc_id, 'rb'),
64
65
66
67
                mimetype='text/plain',
                as_attachment=True,
                attachment_filename='%s.log' % archive_id)
        except Restricted:
68
            abort(401, message='Not authorized to access %s/%s.' % (upload_id, calc_id))
69
70
        except KeyError:
            abort(404, message='Calculation %s does not exist.' % archive_id)
71
72
73
74


@calc_route(ns)
class ArchiveCalcResource(Resource):
75
    @api.doc('get_archive_calc')
76
    @api.response(404, 'The upload or calculation does not exist')
77
    @api.response(401, 'Not authorized to access the data.')
78
    @api.response(200, 'Archive data send')
79
    @authenticate(signature_token=True)
80
    def get(self, upload_id, calc_id):
81
82
83
        """
        Get calculation data in archive form.

84
        Calcs are references via *upload_id*, *calc_id* pairs.
85
        """
86
        archive_id = '%s/%s' % (upload_id, calc_id)
87

88
        upload_file = UploadFiles.get(
89
            upload_id, is_authorized=create_authorization_predicate(upload_id, calc_id))
90

91
        if upload_file is None:
92
            abort(404, message='Archive %s does not exist.' % upload_id)
93
94
95

        try:
            return send_file(
96
                upload_file.archive_file(calc_id, 'rb'),
97
98
99
100
                mimetype='application/json',
                as_attachment=True,
                attachment_filename='%s.json' % archive_id)
        except Restricted:
101
            abort(401, message='Not authorized to access %s/%s.' % (upload_id, calc_id))
102
        except KeyError:
103
            abort(404, message='Calculation %s does not exist.' % archive_id)
104
105


106
107
@ns.route('/metainfo/<string:metainfo_package_name>')
@api.doc(params=dict(metainfo_package_name='The name of the metainfo package.'))
108
109
110
111
class MetainfoResource(Resource):
    @api.doc('get_metainfo')
    @api.response(404, 'The metainfo does not exist')
    @api.response(200, 'Metainfo data send')
112
    def get(self, metainfo_package_name):
113
114
115
116
        """
        Get a metainfo definition file.
        """
        try:
117
            return load_metainfo(metainfo_package_name), 200
118
        except FileNotFoundError:
119
            parser_prefix = metainfo_package_name[:-len('.nomadmetainfo.json')]
120

121
            try:
122
123
124
                return load_metainfo(dict(
                    parser='%sparser' % parser_prefix,
                    path='%s.nomadmetainfo.json' % parser_prefix)), 200
125
126
            except FileNotFoundError:
                abort(404, message='The metainfo %s does not exist.' % metainfo_package_name)
127
128
129
130
131


metainfo_main_path = os.path.dirname(os.path.abspath(nomad_meta_info.__file__))


132
133
134
def load_metainfo(
        package_name_or_dependency: str, dependency_source: str = None,
        loaded_packages: Dict[str, Any] = None) -> Dict[str, Any]:
135
136
137
138
139
    """
    Loads the given metainfo package and all its dependencies. Returns a dict with
    all loaded package_names and respective packages.

    Arguments:
140
141
        package_name_or_dependency: The name of the package, or a nomadmetainfo dependency object.
        dependency_source: The path of the metainfo that uses this function to load a relative dependency.
142
143
144
145
146
147
        loaded_packages: Give a dict and the function will added freshly loaded packages
            to it and return it.
    """
    if loaded_packages is None:
        loaded_packages = {}

148
149
    if isinstance(package_name_or_dependency, str):
        package_name = package_name_or_dependency
150
        metainfo_path = os.path.join(metainfo_main_path, package_name)
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
    else:
        dependency = package_name_or_dependency
        if 'relativePath' in dependency:
            if dependency_source is None:
                raise Exception(
                    'Can only load relative dependency from within another metainfo package')

            metainfo_path = os.path.join(
                os.path.dirname(dependency_source), dependency['relativePath'])

        elif 'metainfoPath' in dependency:
            metainfo_path = os.path.join(metainfo_main_path, dependency['metainfoPath'])

        elif 'parser' in dependency:
            parser = dependency['parser']
            path = dependency['path']
            try:
                parser_module = importlib.import_module(parser).__file__
            except Exception:
                raise Exception('Parser not installed %s for metainfo path %s' % (parser, metainfo_path))

            parser_directory = os.path.dirname(parser_module)
            metainfo_path = os.path.join(parser_directory, path)

        else:
            raise Exception('Invalid dependency type in metainfo package %s' % metainfo_path)

        package_name = os.path.basename(metainfo_path)
179
180
181
182
183
184
185
186
187
188
189
190

    package_name = os.path.basename(package_name)

    if package_name in loaded_packages:
        return loaded_packages

    with open(metainfo_path, 'rt') as f:
        metainfo_json = json.load(f)

    loaded_packages[package_name] = metainfo_json

    for dependency in metainfo_json.get('dependencies', []):
191
        load_metainfo(dependency, dependency_source=metainfo_path, loaded_packages=loaded_packages)
192
193

    return loaded_packages