Beispiel #1
0
def business_create(task: Dict[str, Any]) -> Tuple[Content, HttpStatusCode]:
    """Creates new Task db record.
    Fields which require to be of datetime type are explicitly converted here.
    """
    try:
        new_task = Task(
            user_id=task['userId'],
            hostname=task['hostname'],
            command=task['command'],
            # TODO Adjust API spec, optional fields
            spawn_at=DateUtils.try_parse_string(task.get('spawnAt')),
            terminate_at=DateUtils.try_parse_string(task.get('terminateAt')))
        # assert all(task.values()), 'fields cannot be blank or null'
        new_task.save()
    except ValueError:
        # Invalid string format for datetime
        content, status = {'msg': GENERAL['bad_request']}, 422
    except KeyError:
        # At least one of required fields was not present
        content, status = {'msg': GENERAL['bad_request']}, 422
    except AssertionError as e:
        content, status = {
            'msg': TASK['create']['failure']['invalid'].format(reason=e)
        }, 422
    except Exception as e:
        log.critical(e)
        content, status = {'msg': GENERAL['internal_error']}, 500
    else:
        content, status = {
            'msg': TASK['create']['success'],
            'task': new_task.as_dict()
        }, 201
    finally:
        return content, status
Beispiel #2
0
 def stop_at(self, value):
     if value is not None:
         self._stop_at = DateUtils.try_parse_string(value)
         if self._stop_at is None:
             log.error('Unsupported type (start_at={})'.format(value))
     else:
         self._stop_at = None
Beispiel #3
0
def create(restriction: Dict[str, Any]) -> Tuple[Content, HttpStatusCode]:
    try:
        new_restriction = Restriction(name=restriction.get('name'),
                                      starts_at=restriction['startsAt'],
                                      is_global=restriction['isGlobal'],
                                      ends_at=DateUtils.try_parse_string(
                                          restriction.get('endsAt')))
        new_restriction.save()
    except AssertionError as e:
        content = {
            'msg': RESTRICTION['create']['failure']['invalid'].format(reason=e)
        }
        status = HTTPStatus.UNPROCESSABLE_ENTITY.value
    except Exception as e:
        content = {'msg': GENERAL['internal_error'] + str(e)}
        status = HTTPStatus.INTERNAL_SERVER_ERROR.value
    else:
        content = {
            'msg':
            RESTRICTION['create']['success'],
            'restriction':
            new_restriction.as_dict(include_groups=True,
                                    include_users=True,
                                    include_resources=True)
        }
        status = HTTPStatus.CREATED.value
    finally:
        return content, status
Beispiel #4
0
 def start_at(self, value):
     if value is not None:
         self._start_at = DateUtils.try_parse_string(value)
         if self._start_at is None:
             log.error('Unsupported type (start_at={})'.format(value))
         else:
             assert self._start_at > datetime.utcnow(
             ), 'Job start time must be in the future!'
     else:
         self._start_at = None
Beispiel #5
0
def create(reservation: Dict[str, Any]) -> Tuple[Content, HttpStatusCode]:
    try:
        new_reservation = Reservation(title=reservation['title'],
                                      description=reservation['description'],
                                      resource_id=reservation['resourceId'],
                                      user_id=reservation['userId'],
                                      start=reservation['start'],
                                      end=reservation['end'])

        if not is_admin() and not __is_reservation_owner(new_reservation):
            raise ForbiddenException(
                "Cannot reserve resources in another user's name")

        reservation_start = DateUtils.try_parse_string(new_reservation.start)
        request_time_limit = timedelta(minutes=1)
        starts_in_the_future = (reservation_start +
                                request_time_limit) >= datetime.utcnow()
        if not is_admin() and not starts_in_the_future:
            raise ForbiddenException("Cannot reserve resources in the past")

        user = User.get(get_jwt_identity())
        if not ReservationVerifier.is_reservation_allowed(
                user, new_reservation):
            raise ForbiddenException("Reservation not allowed")

        new_reservation.save()
        content = {
            'msg': RESERVATION['create']['success'],
            'reservation': new_reservation.as_dict()
        }
        status = 201
    except ForbiddenException as e:
        content = {
            'msg':
            RESERVATION['create']['failure']['forbidden'].format(reason=e)
        }
        status = 403
    except AssertionError as e:
        content = {
            'msg': RESERVATION['create']['failure']['invalid'].format(reason=e)
        }
        status = 422
    except Exception as e:
        print(e)
        content = {'msg': GENERAL['internal_error'] + str(e)}
        status = 500
    finally:
        return content, status
Beispiel #6
0
def business_update(
        id: TaskId, new_values: Dict[str,
                                     Any]) -> Tuple[Content, HttpStatusCode]:
    """Updates certain fields of a Task db record, see `allowed_fields`."""
    allowed_fields = {'command', 'hostname', 'spawnAt', 'terminateAt'}
    try:
        assert set(new_values.keys()).issubset(
            allowed_fields), 'invalid field is present'
        task = Task.get(id)
        for field_name, new_value in new_values.items():
            if field_name in {'spawnAt', 'terminateAt'}:
                new_value = DateUtils.try_parse_string(new_value)
            field_name = snakecase(field_name)
            # Check that every field matches
            assert (field_name is not None) and hasattr(
                task, field_name), 'task has no {} field'.format(field_name)
            setattr(task, field_name, new_value)
        task.save()
    except NoResultFound:
        content, status = {'msg': TASK['not_found']}, 404
    except ValueError:
        # Invalid string format for datetime
        content, status = {'msg': GENERAL['bad_request']}, 422
    except AssertionError as e:
        content, status = {
            'msg': TASK['update']['failure']['assertions'].format(reason=e)
        }, 422
    except Exception as e:
        log.critical(e)
        content, status = {'msg': GENERAL['internal_error']}, 500
    else:
        content, status = {
            'msg': TASK['update']['success'],
            'task': task.as_dict()
        }, 201
    finally:
        return content, status
Beispiel #7
0
 def created_at(self, value: str):
     self._created_at = DateUtils.try_parse_string(value)
     if self._created_at is None:
         log.error('Unsupported type (created_at={})'.format(value))
Beispiel #8
0
 def ends_at(self, value: str):
     self._ends_at = DateUtils.try_parse_string(value)
Beispiel #9
0
 def end(self, value):
     self._end = DateUtils.try_parse_string(value)
     if self._end is None:
         log.error('Unsupported type (end={})'.format(value))
Beispiel #10
0
 def start(self, value):
     self._start = DateUtils.try_parse_string(value)
     if self._start is None:
         log.error('Unsupported type (start={})'.format(value))