api_endpoint.py 9.31 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Copyright (c) 2016, Daniele Venzano
#
# 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 real API, exposed as web pages or REST API."""

import logging
19
import os
20
from typing import Mapping
21

22
23
import zoe_api.exceptions
import zoe_api.master_api
24
25
import zoe_lib.applications
import zoe_lib.exceptions
26
27
import zoe_lib.state
from zoe_lib.config import get_conf
28
29
30
31
32
33
34
35
36
37
38

log = logging.getLogger(__name__)


class APIEndpoint:
    """
    The APIEndpoint class.

    :type master: zoe_api.master_api.APIManager
    :type sql: zoe_lib.sql_manager.SQLManager
    """
39
    def __init__(self, master_api, sql_manager: zoe_lib.state.SQLManager):
40
41
        self.master = master_api
        self.sql = sql_manager
42

43
    def execution_by_id(self, uid: zoe_lib.state.User, role: zoe_lib.state.Role, execution_id: int) -> zoe_lib.state.Execution:
44
        """Lookup an execution by its ID."""
45
        e = self.sql.executions.select(id=execution_id, only_one=True)
46
47
        if e is None:
            raise zoe_api.exceptions.ZoeNotFoundException('No such execution')
48
        assert isinstance(e, zoe_lib.state.Execution)
49
        if e.user_id != uid.id and not role.can_operate_others:
50
51
52
            raise zoe_api.exceptions.ZoeAuthException()
        return e

53
    def execution_list(self, uid: zoe_lib.state.User, role: zoe_lib.state.Role, **filters: Mapping[str, str]):
54
        """Generate a optionally filtered list of executions."""
55
56
        if not role.can_operate_others:
            filters['user_id'] = uid.id
57
        execs = self.sql.executions.select(**filters)
58
59
        return execs

60
    def execution_count(self, uid: zoe_lib.state.User, role: zoe_lib.state.Role, **filters: Mapping[str, str]):
61
        """Count the number of executions optionally filtered."""
62
63
        if not role.can_operate_others:
            filters['user_id'] = uid.id
64
65
        execs = self.sql.executions.count(**filters)
        return execs
66

67
68
69
70
71
72
73
    def zapp_validate(self, application_description):
        """Validates the passed ZApp description against the supported schema."""
        try:
            zoe_lib.applications.app_validate(application_description)
        except zoe_lib.exceptions.InvalidApplicationDescription as e:
            raise zoe_api.exceptions.ZoeException('Invalid application description: ' + e.message)

74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
    def _check_quota(self, user: zoe_lib.state.User, application_description):  # pylint: disable=unused-argument
        """Check quota for given user and execution."""
        quota = self.sql.quota.select(only_one=True, **{'id': user.quota_id})

        running_execs = self.sql.executions.select(**{'status': 'running', 'user_id': user.id})
        running_execs += self.sql.executions.select(**{'status': 'starting', 'user_id': user.id})
        running_execs += self.sql.executions.select(**{'status': 'scheduled', 'user_id': user.id})
        running_execs += self.sql.executions.select(**{'status': 'image download', 'user_id': user.id})
        running_execs += self.sql.executions.select(**{'status': 'submitted', 'user_id': user.id})
        if len(running_execs) >= quota.concurrent_executions:
            raise zoe_api.exceptions.ZoeException('You cannot run more than {} executions at a time, quota exceeded.'.format(quota.concurrent_executions))

        # TODO: implement core and memory quotas

    def execution_start(self, uid: zoe_lib.state.User, role: zoe_lib.state.Role, exec_name, application_description):  # pylint: disable=unused-argument
89
90
91
92
93
94
        """Start an execution."""
        try:
            zoe_lib.applications.app_validate(application_description)
        except zoe_lib.exceptions.InvalidApplicationDescription as e:
            raise zoe_api.exceptions.ZoeException('Invalid application description: ' + e.message)

95
96
97
        self._check_quota(uid, application_description)

        new_id = self.sql.executions.insert(exec_name, uid.id, application_description)
98
99
100
        success, message = self.master.execution_start(new_id)
        if not success:
            raise zoe_api.exceptions.ZoeException('The Zoe master is unavailable, execution will be submitted automatically when the master is back up ({}).'.format(message))
hxquangnhat's avatar
hxquangnhat committed
101

102
103
        return new_id

104
    def execution_terminate(self, uid: zoe_lib.state.User, role: zoe_lib.state.Role, exec_id: int):
105
        """Terminate an execution."""
106
107
        e = self.sql.executions.select(id=exec_id, only_one=True)
        assert isinstance(e, zoe_lib.state.Execution)
108
109
110
        if e is None:
            raise zoe_api.exceptions.ZoeNotFoundException('No such execution')

111
        if e.user_id != uid.id and not role.can_operate_others:
112
113
            raise zoe_api.exceptions.ZoeAuthException()

114
        if e.is_active:
115
116
117
118
            return self.master.execution_terminate(exec_id)
        else:
            raise zoe_api.exceptions.ZoeException('Execution is not running')

119
    def execution_delete(self, uid: zoe_lib.state.User, role: zoe_lib.state.Role, exec_id: int):
120
        """Delete an execution."""
121
        if not role.can_delete_executions:
122
123
            raise zoe_api.exceptions.ZoeAuthException()

124
125
        e = self.sql.executions.select(id=exec_id, only_one=True)
        assert isinstance(e, zoe_lib.state.Execution)
126
127
128
        if e is None:
            raise zoe_api.exceptions.ZoeNotFoundException('No such execution')

129
        if e.user_id != uid.id and not role.can_operate_others:
130
131
            raise zoe_api.exceptions.ZoeAuthException()

132
        if e.is_active:
133
            raise zoe_api.exceptions.ZoeException('Cannot delete an active execution')
134
135
136

        status, message = self.master.execution_delete(exec_id)
        if status:
137
            self.sql.executions.delete(exec_id)
138
139
140
141
            return True, ''
        else:
            raise zoe_api.exceptions.ZoeException(message)

142
    def service_by_id(self, uid: zoe_lib.state.User, role: zoe_lib.state.Role, service_id: int) -> zoe_lib.state.Service:
143
        """Lookup a service by its ID."""
144
        service = self.sql.services.select(id=service_id, only_one=True)
145
146
        if service is None:
            raise zoe_api.exceptions.ZoeNotFoundException('No such execution')
147
        if service.user_id != uid.id and not role.can_operate_others:
148
149
150
            raise zoe_api.exceptions.ZoeAuthException()
        return service

151
    def service_list(self, uid: zoe_lib.state.User, role: zoe_lib.state.Role, **filters):
152
        """Generate a optionally filtered list of services."""
153
154
155
        if not role.can_operate_others:
            filters['user_id'] = uid.id
        return self.sql.services.select(**filters)
156

157
    def service_logs(self, uid: zoe_lib.state.User, role: zoe_lib.state.Role, service_id):
158
159
160
        """Retrieve the logs for the given service.
        If stream is True, a file object is returned, otherwise the log contents as a str object.
        """
161
        service = self.sql.services.select(id=service_id, only_one=True)
162
163
        if service is None:
            raise zoe_api.exceptions.ZoeNotFoundException('No such service')
164
        if service.user_id != uid.id and not role.can_operate_others:
165
            raise zoe_api.exceptions.ZoeAuthException()
166
167
168
169

        path = os.path.join(get_conf().service_logs_base_path, get_conf().deployment_name, str(service.execution_id), service.name + '.txt')
        if not os.path.exists(path):
            raise zoe_api.exceptions.ZoeNotFoundException('Service log not available')
170
        return open(path, encoding='utf-8')
171

172
173
    def statistics_scheduler(self, uid_, role_):
        """Retrieve statistics about the scheduler."""
174
175
        success, message = self.master.scheduler_statistics()
        if success:
176
177
178
179
            for node in message['platform_stats']['nodes']:  # JSON does not like hash keys to be integers, so we need to convert manually
                for str_service_id in list(node['service_stats'].keys()):
                    node['service_stats'][int(str_service_id)] = node['service_stats'][str_service_id]
                    del node['service_stats'][str_service_id]
180
            return message
Daniele Venzano's avatar
Daniele Venzano committed
181
182
        else:
            raise zoe_api.exceptions.ZoeException(message=message)
183

184
    def execution_endpoints(self, uid: zoe_lib.state.User, role: zoe_lib.state.Role, execution: zoe_lib.state.Execution):
185
186
187
188
189
190
        """Return a list of the services and public endpoints available for a certain execution."""
        services_info = []
        endpoints = []
        for service in execution.services:
            services_info.append(self.service_by_id(uid, role, service.id))
            for port in service.description['ports']:
191
                port_key = str(port['port_number']) + "/" + port['protocol']
192
                backend_port = self.sql.ports.select(only_one=True, service_id=service.id, internal_name=port_key)
193
                if backend_port is not None and backend_port.external_ip is not None:
194
                    endpoint = port['url_template'].format(**{"ip_port": backend_port.external_ip + ":" + str(backend_port.external_port)})
195
                    endpoints.append((port['name'], endpoint))
196
197

        return services_info, endpoints