api_endpoint.py 19.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 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."""

18
from datetime import timedelta, datetime
19
import logging
20
import os
21
from typing import List, Union
22

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

log = logging.getLogger(__name__)


class APIEndpoint:
    """
    The APIEndpoint class.

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

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

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

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

67 68 69 70 71
    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:
72
            raise zoe_api.exceptions.ZoeRestAPIException('Invalid application description: {}'.format(e.message), status_code=400)
73

74
    def _check_quota(self, user: zoe_lib.state.User, application_description):
75 76 77 78 79
        """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})
80
        running_execs += self.sql.executions.select(**{'status': 'queued', 'user_id': user.id})
81 82
        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})
83
        if quota.concurrent_executions != 0 and len(running_execs) >= quota.concurrent_executions:
84
            raise zoe_api.exceptions.ZoeQuotaException('You cannot run more than {} executions at a time, quota exceeded.'.format(quota.concurrent_executions))
85

86 87 88 89 90 91
        if quota.cores != 0 and quota.memory != 0:
            return

        reserved_cores = 0
        reserved_mem = 0
        for e in running_execs:
Daniele Venzano's avatar
Daniele Venzano committed
92 93 94
            for service in e.services:
                reserved_cores += service.resource_reservation.cores.min
                reserved_mem += service.resource_reservation.memory.min
95 96 97

        new_exec_cores = 0
        new_exec_memory = 0
Daniele Venzano's avatar
Daniele Venzano committed
98 99 100
        for service in application_description['services']:
            new_exec_cores += service['resources']['cores']['min'] * service['total_count']
            new_exec_memory += service['resources']['memory']['min'] * service['total_count']
101 102 103 104 105

        if quota.cores < reserved_cores + new_exec_cores:
            raise zoe_api.exceptions.ZoeQuotaException('You requested {} cores more than your quota allows, quota exceeded.'.format((reserved_cores + new_exec_cores) - quota.cores))
        if quota.memory < reserved_mem + new_exec_memory:
            raise zoe_api.exceptions.ZoeQuotaException('You requested {}B memory more than your quota allows, quota exceeded.'.format((reserved_mem + new_exec_memory) - quota.memory))
106

107
    def execution_start(self, user: zoe_lib.state.User, exec_name, application_description):
108 109 110 111
        """Start an execution."""
        try:
            zoe_lib.applications.app_validate(application_description)
        except zoe_lib.exceptions.InvalidApplicationDescription as e:
112
            raise zoe_api.exceptions.ZoeRestAPIException('Invalid application description: ' + e.message)
113

114
        self._check_quota(user, application_description)
115

116
        new_id = self.sql.executions.insert(exec_name, user.id, application_description)
117 118
        success, message = self.master.execution_start(new_id)
        if not success:
119
            raise zoe_api.exceptions.ZoeRestAPIException('The Zoe master is unavailable, execution will be submitted automatically when the master is back up ({}).'.format(message), status_code=503)
hxquangnhat's avatar
hxquangnhat committed
120

121 122
        return new_id

123
    def execution_terminate(self, user: zoe_lib.state.User, exec_id: int, reason: str):
124
        """Terminate an execution."""
125 126
        e = self.sql.executions.select(id=exec_id, only_one=True)
        assert isinstance(e, zoe_lib.state.Execution)
127 128 129
        if e is None:
            raise zoe_api.exceptions.ZoeNotFoundException('No such execution')

130
        if e.user_id != user.id and not user.role.can_operate_others:
131
            raise zoe_api.exceptions.ZoeAuthException('You are not authorized to terminate this execution')
132

133
        if e.is_active:
134
            success, message = self.master.execution_terminate(exec_id, reason)
135 136
            if not success:
                raise zoe_api.exceptions.ZoeRestAPIException(message)
137
        else:
138
            raise zoe_api.exceptions.ZoeRestAPIException('Execution is not running')
139

140
    def execution_delete(self, user: zoe_lib.state.User, exec_id: int):
141
        """Delete an execution."""
142
        if not user.role.can_delete_executions:
143 144
            raise zoe_api.exceptions.ZoeAuthException()

145 146
        e = self.sql.executions.select(id=exec_id, only_one=True)
        assert isinstance(e, zoe_lib.state.Execution)
147 148 149
        if e is None:
            raise zoe_api.exceptions.ZoeNotFoundException('No such execution')

150
        if e.user_id != user.id and not user.role.can_operate_others:
151
            raise zoe_api.exceptions.ZoeAuthException('You are not authorized to terminate this execution')
152

153
        if e.is_active:
154
            raise zoe_api.exceptions.ZoeRestAPIException('Cannot delete an active execution')
155 156 157

        status, message = self.master.execution_delete(exec_id)
        if status:
158
            self.sql.executions.delete(exec_id)
159
        else:
160
            raise zoe_api.exceptions.ZoeRestAPIException(message)
161

162
    def service_by_id(self, user: zoe_lib.state.User, service_id: int) -> zoe_lib.state.Service:
163
        """Lookup a service by its ID."""
164
        service = self.sql.services.select(id=service_id, only_one=True)
165 166
        if service is None:
            raise zoe_api.exceptions.ZoeNotFoundException('No such execution')
167
        if service.user_id != user.id and not user.role.can_operate_others:
168 169 170
            raise zoe_api.exceptions.ZoeAuthException()
        return service

171
    def service_list(self, user: zoe_lib.state.User, **filters):
172
        """Generate a optionally filtered list of services."""
173 174
        if not user.role.can_operate_others:
            filters['user_id'] = user.id
175
        return self.sql.services.select(**filters)
176

177
    def service_logs(self, user: zoe_lib.state.User, service_id):
178 179 180
        """Retrieve the logs for the given service.
        If stream is True, a file object is returned, otherwise the log contents as a str object.
        """
181
        service = self.sql.services.select(id=service_id, only_one=True)
182 183
        if service is None:
            raise zoe_api.exceptions.ZoeNotFoundException('No such service')
184
        if service.user_id != user.id and not user.role.can_operate_others:
185
            raise zoe_api.exceptions.ZoeAuthException()
186 187 188 189

        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')
190
        return open(path, encoding='utf-8')
191

192
    def statistics_scheduler(self):
193
        """Retrieve statistics about the scheduler."""
194 195
        success, message = self.master.scheduler_statistics()
        if success:
196 197 198 199
            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]
200
            return message
Daniele Venzano's avatar
Daniele Venzano committed
201 202
        else:
            raise zoe_api.exceptions.ZoeException(message=message)
203

204
    def execution_endpoints(self, user: zoe_lib.state.User, execution: zoe_lib.state.Execution):
205 206 207 208
        """Return a list of the services and public endpoints available for a certain execution."""
        services_info = []
        endpoints = []
        for service in execution.services:
209
            services_info.append(self.service_by_id(user, service.id))
210 211 212 213 214 215 216 217
            for port in service.ports:
                if port.external_ip is not None:
                    endpoint = port.url_template.format(**{"ip_port": port.external_ip + ":" + str(port.external_port)})
                    if zoe_lib.config.get_conf().traefik_zk_ips is None:
                        endpoint_ext = None
                    else:
                        endpoint_ext = '/{}/{}'.format(zoe_lib.config.get_conf().traefik_base_url, port.proxy_key())
                    endpoints.append((port.name, endpoint, endpoint_ext))
218 219

        return services_info, endpoints
220

221
    def user_by_name(self, username) -> zoe_lib.state.User:
222 223
        """Finds a user in the database looking it up by its username."""
        return self.sql.user.select(only_one=True, **{'username': username})
224 225 226 227 228

    def user_by_id(self, user: zoe_lib.state.User, user_id: int) -> zoe_lib.state.User:
        """Finds a user in the database looking it up by its username."""
        if user.id == user_id:
            return user
229
        if not user.role.can_change_config:
230 231
            raise zoe_api.exceptions.ZoeAuthException()

232 233 234 235 236
        ret = self.sql.user.select(only_one=True, id=user_id)
        if ret is None:
            raise zoe_api.exceptions.ZoeNotFoundException("No such user")
        else:
            return ret
237 238 239 240 241 242

    def user_delete(self, user: zoe_lib.state.User, user_id: int):
        """Deletes the user identified by the ID."""
        if not user.role.can_change_config:
            raise zoe_api.exceptions.ZoeAuthException()

243 244 245 246
        user_to_del = self.user_by_id(user, user_id)
        if user_to_del.username == "admin":
            raise zoe_api.exceptions.ZoeRestAPIException('The admin user cannot be deleted, but it can be disabled')

247
        self.sql.user.delete(user_id)
248 249

    def user_list(self, user: zoe_lib.state.User, **filters) -> List[zoe_lib.state.User]:
250
        """Generate a optionally filtered list of users."""
251 252 253 254 255
        if not user.role.can_change_config:
            raise zoe_api.exceptions.ZoeAuthException()
        users = self.sql.user.select(**filters)
        return users

256
    def user_new(self, user: zoe_lib.state.User, username: str, email: str, role_id: int, quota_id: int, auth_source: str, fs_uid: int) -> int:  # pylint: disable=too-many-arguments
257 258 259 260
        """Creates a new user."""
        if not user.role.can_change_config:
            raise zoe_api.exceptions.ZoeAuthException()

261 262 263 264 265
        if self.role_by_id(role_id) is None:
            raise zoe_api.exceptions.ZoeNotFoundException("Role {} does not exist".format(role_id))
        if self.quota_by_id(quota_id) is None:
            raise zoe_api.exceptions.ZoeNotFoundException("Quota {} does not exist".format(quota_id))

266
        return self.sql.user.insert(username, email, auth_source, role_id, quota_id, fs_uid)
267

268
    def user_update(self, user: zoe_lib.state.User, user_id, user_data):
269 270
        """Update a user."""

271
        self.user_by_id(user, user_id)
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286

        update_fields = {}

        if not user.role.can_change_config:
            if 'email' in user_data:
                update_fields['email'] = user_data['email']
        else:
            if 'email' in user_data:
                update_fields['email'] = user_data['email']
            if 'priority' in user_data:
                update_fields['priority'] = user_data['priority']
            if 'enabled' in user_data:
                update_fields['enabled'] = user_data['enabled']
            if 'auth_source' in user_data:
                update_fields['auth_source'] = user_data['auth_source']
287
                if user_data['auth_source'] != 'internal':
288
                    update_fields['password'] = None
289 290
            if 'quota_id' in user_data:
                quota = self.quota_by_id(user_data['quota_id'])
291
                if quota is None:
292
                    raise zoe_api.exceptions.ZoeRestAPIException('No quota with ID {}'.format(user_data['quota_id']))
293
                update_fields['quota_id'] = quota.id
294
            if 'role_id' in user_data:
295
                role = self.role_by_id(user_data['role_id'])
296
                if role is None:
297
                    raise zoe_api.exceptions.ZoeRestAPIException('No role with ID {}'.format(user_data['role_id']))
298
                update_fields['role_id'] = role.id
299 300
            if 'password' in user_data:
                update_fields['password'] = user_data['password']
301 302
            if 'fs_uid' in user_data:
                update_fields['fs_uid'] = user_data['fs_uid']
303

304
        self.sql.user.update(user_id, **update_fields)
305 306 307 308 309

    def quota_by_name(self, quota) -> zoe_lib.state.Quota:
        """Finds a quota in the database looking it up by its name."""
        return self.sql.quota.select(only_one=True, **{'name': quota})

310 311
    def quota_by_id(self, quota_id) -> zoe_lib.state.Quota:
        """Finds a quota in the database looking it up by its id."""
312 313 314 315 316
        quota = self.sql.quota.select(only_one=True, **{'id': quota_id})
        if quota is None:
            raise zoe_api.exceptions.ZoeNotFoundException('No such quota')
        else:
            return quota
317

318 319 320
    def role_by_name(self, role) -> zoe_lib.state.Role:
        """Finds a role in the database looking it up by its name."""
        return self.sql.role.select(only_one=True, **{'name': role})
321 322 323

    def role_by_id(self, role_id) -> zoe_lib.state.Role:
        """Finds a role in the database looking it up by its id."""
324 325 326 327 328
        role = self.sql.role.select(only_one=True, **{'id': role_id})
        if role is None:
            raise zoe_api.exceptions.ZoeNotFoundException('No such role')
        else:
            return role
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350

    def role_new(self, user: zoe_lib.state.User, role_data) -> int:
        """Creates a new role."""
        if not user.role.can_change_config:
            raise zoe_api.exceptions.ZoeAuthException()

        role_id = self.sql.role.insert(role_data['name'])
        self.sql.role.update(role_id, **role_data)
        return role_id

    def role_list(self, user: zoe_lib.state.User, **filters) -> List[zoe_lib.state.Role]:
        """Generate a optionally filtered list of roles."""
        if not user.role.can_change_config:
            raise zoe_api.exceptions.ZoeAuthException()
        users = self.sql.role.select(**filters)
        return users

    def role_delete(self, user: zoe_lib.state.User, role_id: int):
        """Deletes the role identified by the ID."""
        if not user.role.can_change_config:
            raise zoe_api.exceptions.ZoeAuthException()

351
        role = self.role_by_id(role_id)
352 353
        if role.name == "admin":
            raise zoe_api.exceptions.ZoeRestAPIException('Cannot delete admin role')
354

355 356
        self.sql.role.delete(role_id)

357
    def role_update(self, user: zoe_lib.state.User, role_id: int, role_data):
358 359 360 361
        """Update a role."""
        if not user.role.can_change_config:
            raise zoe_api.exceptions.ZoeAuthException()

362
        role = self.role_by_id(role_id)
363

364 365
        if role.name == "admin":
            raise zoe_api.exceptions.ZoeRestAPIException('Cannot edit the admin role')
366 367

        self.sql.role.update(role_id, **role_data)
368 369 370 371 372 373

    def quota_new(self, user: zoe_lib.state.User, quota_data) -> int:
        """Creates a new quota."""
        if not user.role.can_change_config:
            raise zoe_api.exceptions.ZoeAuthException()

374
        role_id = self.sql.quota.insert(quota_data['name'], quota_data['concurrent_executions'], quota_data['memory'], quota_data['cores'], quota_data['runtime_limit'])
375 376 377 378 379 380 381 382 383 384 385 386 387 388
        return role_id

    def quota_list(self, user: zoe_lib.state.User, **filters) -> List[zoe_lib.state.Quota]:
        """Generate a optionally filtered list of quotas."""
        if not user.role.can_change_config:
            raise zoe_api.exceptions.ZoeAuthException()
        users = self.sql.quota.select(**filters)
        return users

    def quota_delete(self, user: zoe_lib.state.User, quota_id: int):
        """Deletes the quota identified by the ID."""
        if not user.role.can_change_config:
            raise zoe_api.exceptions.ZoeAuthException()

389 390 391 392 393 394
        quota = self.quota_by_id(quota_id)
        if quota is None:
            raise zoe_api.exceptions.ZoeNotFoundException('No such quota')
        if quota.name == "default":
            raise zoe_api.exceptions.ZoeRestAPIException('Cannot delete default quota')

395 396
        self.sql.quota.delete(quota_id)

397
    def quota_update(self, user: zoe_lib.state.User, quota_id, quota_data):
398 399 400 401
        """Update a quota."""
        if not user.role.can_change_config:
            raise zoe_api.exceptions.ZoeAuthException()

402 403 404
        quota = self.quota_by_id(quota_id)
        if quota.name == "default" and "name" in quota_data:
            raise zoe_api.exceptions.ZoeRestAPIException('Cannot rename default quota')
405

406
        self.sql.quota.update(quota_id, **quota_data)
407 408 409 410 411

    def verify_runtime_limit(self):
        """Scan the active executions and kill all those that exceed the runtime_limit quota."""
        running_execs = self.sql.executions.select(**{'status': 'running'})
        running_execs += self.sql.executions.select(**{'status': 'starting'})
412
        running_execs += self.sql.executions.select(**{'status': 'queued'})
413 414 415 416 417 418 419 420
        running_execs += self.sql.executions.select(**{'status': 'image download'})
        running_execs += self.sql.executions.select(**{'status': 'submitted'})

        for e in running_execs:
            runtime_limit = e.owner.quota.runtime_limit
            if runtime_limit == 0:
                continue
            runtime_limit = timedelta(hours=runtime_limit)
421
            if e.time_submit + runtime_limit < datetime.utcnow():
422
                log.info('Automatically terminating execution {} that has exceeded the run time limit'.format(e.id))
423
                self.execution_terminate(e.owner, e.id, 'Run time quota exceeded')