def get(cls, id): try: result = db_session.query(cls).filter_by(id=id).one() except MultipleResultsFound: msg = 'There are multiple {} records with the same id={}!'.format(cls.__name__, id) log.critical(msg) raise MultipleResultsFound(msg) except NoResultFound: msg = 'There is no record {} with id={}!'.format(cls.__name__, id) log.debug(msg) raise NoResultFound(msg) else: return result
def find_by_name(cls, name): try: result = db_session.query(cls).filter_by(name=name).one() except MultipleResultsFound: # Theoretically cannot happen because of model built-in constraints msg = 'Multiple command segments with identical names has been found!' log.critical(msg) raise MultipleResultsFound(msg) except NoResultFound: msg = 'There is no command segment with name={}!'.format(name) log.warning(msg) raise NoResultFound(msg) else: return result
def terminate_scheduled(self, now: datetime): """Triggers `terminate` on database records that should not be running. It will stop trying after `self.stop_attempts_after` because it means that process is unable to kill and probably requires human (owner/admin) intervention. Current behavior: - Gets only those tasks which were scheduled to terminate within last X seconds/minutes/whatever - Ignores tasks which were not able to terminate by that time It improves performance, because we don't have to check every single task from the past. Author's note: - Controller implementation takes full responsibility for termination logic. """ consideration_threshold = now - self.stop_attempts_after recently_scheduled = and_(Task.terminate_at.isnot(None), Task.terminate_at > consideration_threshold) after_spawn = or_(Task.spawn_at < Task.terminate_at, Task.spawn_at.isnot(None)) can_terminate_now = Task.terminate_at < now # TODO Try replacing with Task.query.filter tasks_to_terminate = db_session.query(Task).filter( recently_scheduled, after_spawn, can_terminate_now).all() log.debug('{} tasks should be terminated.'.format( len(tasks_to_terminate))) for task in tasks_to_terminate: content, status = business_terminate(task.id, gracefully=False) log.info( self._log_msg(now=now, action='Killing', id=task.id, scheduled=task.terminate_at)) if status == 201: log.debug(content['exit_code']) else: log.warning(content['msg'])
def get_by_hostname(cls, hostname): return db_session.query(Resource).filter( Resource.hostname == hostname).all()
def get_by_name(cls, resource_name): return db_session.query(Resource).filter( Resource.name == resource_name).all()
def get_global_restrictions(cls, include_expired=False): query = db_session.query(Restriction).filter(Restriction.is_global.is_(True)) if not include_expired: query.filter(Restriction.is_expired is False) return query.all()
def all(cls): return db_session.query(cls).all()