Пример #1
0
 def __init__(self):
     """create a Worker object"""
     self.logger = worker.log.setup()
     self.queue = SQSQueue('aichallenge-work', logger=self.logger)
     self.result_queue = SQSQueue('aichallenge-results', logger=self.logger)
Пример #2
0
class Worker(object):
    """responsible for doing the heavy lifting"""

    def __init__(self):
        """create a Worker object"""
        self.logger = worker.log.setup()
        self.queue = SQSQueue('aichallenge-work', logger=self.logger)
        self.result_queue = SQSQueue('aichallenge-results', logger=self.logger)

    def loop(self):
        """find and perform tasks until terminated"""
        # replace this with the actual processing logic
        self.logger.info('started')
        while True:
            try:
                message = self.queue.get()
                body = message.get_body()
                self.logger.info('message received: ' + repr(body))
            
                if 'command' not in body:
                    pass
                elif body['command'] == 'run_game':
                    if self.run_game(body):
                        self.queue.delete(message)
            except:
                self.logger.error('Uncaught exception!')
                self.logger.error(traceback.format_exc())
    
    def run_game(self, body):
        """run a game based on the parameters of a queue message body"""
        
        # fetch players from storage if necessary
        teams = self.fetch_and_compile_teams(body['teams'])
        
        # run the game and log the result
        current_game = config.get('worker', 'current_game')
        game_class = worker.games.get_game(current_game)
        game = game_class(body, teams)
        try:
            result = game.run()
            self.logger.info('result: ' + repr(result))
            self.result_queue.put(result)
            return True
        except:
            return False
        finally:
            # Ensure that runner resources are freed
            game.stop()
    
    def fetch_and_compile_teams(self, teams):
        return [[self.fetch_and_compile(player) for player in team]
                    for team in teams]
    
    def fetch_and_compile(self, player):
        worker.storage.fetch(player['submission_hash'], logger=self.logger)
        dir = "$AICHALLENGE_PREFIX/var/lib/aichallenge/submissions/%s"
        dir = os.path.expandvars(dir % player['submission_hash'])
        # TODO: make the submission number meaningful
        subm = Submission(player['name'], 0, dir)
        subm.compile_if_needed(logger=self.logger)
        return subm