def decrement_topic(topic):
    topic_node = "/topics/{}".format(topic)
    queue_node = '/owner_queue/{}'.format(topic)
    if get_topic(topic) is not None and get_topic(topic)[1] > 1:
        cur_strength = get_topic(topic)[1]
        cur_strength -= 1
        new_strength = bytes("{}".format(str(cur_strength)).encode("utf-8"))
        zookeeper.set(topic_node, new_strength)
        zk_queue = Queue(zookeeper, queue_node)
        zk_queue.get()
        print("Topic strength adjusted for pub removal")
    elif get_topic(topic) is not None:
        print("Topic strength adjusted for pub removal, set to 1")
    else:
        print("Topic not found :(")
Ejemplo n.º 2
0
class ScoreWatcher:

    curr_score = []
    high_score = []
    online_players = set()

    def __init__(self, ip_port, score_board_size):
        '''Initialize everyting for the watcher'''
        logging.basicConfig()
        self.score_board_size = score_board_size
        self.is_dump = False
        self.is_init_client = True

        try:
            # Create client
            self.zk = KazooClient(hosts=ip_port, logger=logging)
            self.zk.start()
        except Exception as ex:
            print(
                'Error connecting the Zookeeper Service, Please make sure the service is up or the IP:PORT provided is correct'
            )
            sys.exit(-1)

        # Ensure Paths
        self.zk.ensure_path('/csjain_queue')
        self.zk.ensure_path('/csjain_players')

        # Create Data structures
        self.score_queue = Queue(self.zk, '/csjain_queue')
        self.party = Party(self.zk, '/csjain_players')
        self.online_players = set(self.party)

        if len(self.score_queue) == 0:
            print('Most recent scores')
            print('------------------')
            print('\n')
            print('Highest scores')
            print('--------------')

        # Create Watchers
        _ = ChildrenWatch(self.zk, '/csjain_queue', self.process_score)
        _ = ChildrenWatch(self.zk, '/csjain_players', self.process_client)

    def print_scoreboards(self):
        '''Print the formatted Recent Score and Leader Board'''
        if self.is_dump:
            return

        print('Most recent scores')
        print('------------------')
        if self.curr_score:
            for player, score in self.curr_score:
                if player in self.online_players:
                    print('{}\t\t{}\t**'.format(player, score))
                else:
                    print('{}\t\t{}'.format(player, score))
            print('\n')

        print('Highest scores')
        print('--------------')
        if self.high_score:
            for player, score in self.high_score:
                if player in self.online_players:
                    print('{}\t\t{}\t**'.format(player, score))
                else:
                    print('{}\t\t{}'.format(player, score))
            print('\n')

    def process_score(self, children):
        '''Process any pending score or new score that is posted'''
        if not children:
            return True

        while len(self.score_queue) > 0 and not self.is_dump:
            new_score = self.score_queue.get()

            if not new_score:
                break

            # Update high score
            self.high_score.append(new_score.split(':'))
            self.high_score = sorted(self.high_score,
                                     key=lambda x: float(x[1]),
                                     reverse=True)
            self.high_score = self.high_score[:min(len(self.high_score), self.
                                                   score_board_size)]

            # Update current score
            if not self.curr_score:
                self.curr_score = [new_score.split(':')]
            elif len(self.curr_score) < self.score_board_size:
                self.curr_score = [new_score.split(':')] + self.curr_score
            else:
                self.curr_score = [new_score.split(':')] + self.curr_score[:-1]

        self.print_scoreboards()
        return True

    def process_client(self, children):
        '''Process updates to a player joining or leaving the game'''
        if self.is_init_client:
            self.is_init_client = False
            return True

        self.online_players = set(self.party)
        if self.curr_score:
            self.print_scoreboards()

        return True

    def dump_scoreboard(self):
        self.is_dump = True
        for name, score in self.high_score:
            self.score_queue.put('{}:{}'.format(name, score).encode('utf-8'))