Exemplo n.º 1
0
def mutex_ui(_):
    divide_line()
    print('Welcome to the Mutex UI.')
    print()
    print('1: Request Mutex')
    print('else to exit')
    return mutex_filter(input('\nWhat do you want to do?\n> '))
Exemplo n.º 2
0
def check_members(auth_header, groups):
    divide_line()
    group_id = input(
        'So which groups members are ya lookin for? Your own? [a valid id / y (for own)]\n> '
    )
    if group_id == 'y':
        group_url = get_config()[util_group]
        if group_url != '':
            response = requests.get(group_url + get_config()['member_url'],
                                    headers=auth_header)
            print('Members: ')
            for member in response.json()['objects']:
                print_member(member)
        else:
            print('Well you aint in no group duh.')
    else:
        group_existant = False
        if group_id in groups.keys():
            group_existant = True
        if group_existant:
            response = requests.get(paths_util.group_url_id(group_id) +
                                    get_config()['member_url'],
                                    headers=auth_header)
            print('Members: ')
            for member in response.json()['objects']:
                print_member(member)
        else:
            print('The group with the given id does not exist')
Exemplo n.º 3
0
def get_all_adventureres():
    response = requests.get(paths_util.adventurers_uri(), headers=get_config()[auth_token])
    adventurers = []
    for adventurer in response.json()['objects']:
            adventurers.append(adventurer)
    divide_line()
    return adventurers
Exemplo n.º 4
0
def show_all_groups(auth_header, groups):
    response = requests.get(paths_util.group_url(), headers=auth_header)
    for group in response.json()['objects']:
        groups[str(group['id'])] = group
        print(
            str(group['id']) + ': Owner - ' + group['owner'] + ' | ' +
            str(group['members']) + ' | ' + str(group['_links']))
    divide_line()
Exemplo n.º 5
0
def check_own_group(auth_header, groups):
    divide_line()
    if get_config()[util_group] != '':
        print('Our group: ' + str(get_config()[util_group]))
        response = requests.get(get_config()[util_group], headers=auth_header)
        print(str(response.json()))
    else:
        print('You are in no group!')
Exemplo n.º 6
0
def adventurer_ui(auth_header):
    divide_line()
    print('\nWelcome, this is the place of the adventurers!')
    print()
    print('1: Look at the list behind the bar')
    print('2: Searching for someone?')
    print('Else: Get outta here')
    print()
    return adventurer_filter(input('Which list do you want to see: \n> '), auth_header)
Exemplo n.º 7
0
def join_group(auth_header, groups):
    divide_line()
    group_id = input('Which group do you want to join then? [a valid id]\n> ')
    group_existant = False
    if group_id in groups:
        group_existant = True
    if group_existant:
        post_join_group(group_id)
    else:
        print('The group with this id does not exist')
Exemplo n.º 8
0
def search_ui(auth_header, name):
    divide_line()
    print('And what do you want to do with ' + name + '?')
    print()
    print('1: Look real close! Get all the details.')
    print('2: I dont like, so I change!')
    print('3: Kill.')
    print('4: Hire him? This one? Hahaha, good luck')
    print()
    return search_adv_filter(input('Hm? Tell me. \n> '), auth_header, name)
Exemplo n.º 9
0
def send_message_to_user(auth_header, response_json, user_url):
    divide_line()
    print('It is time to send a message!')
    message = input('Your message:\n> ')
    data = '{"message": "' + message + '"}'
    response = requests.post(user_url + response_json['messages'], data=data)
    if response.status_code == 200 or response.status_code == 201:
        print('The message has successfully been delivered.')
        print('\nAnwser:\n> ' + str(response.json()))
    else:
        print('Message could not be delivered')
Exemplo n.º 10
0
def recv_ok(url, data):
    try:
        response = requests.post(url, data=data)
        print('Reached user ' + url)
        if response.status_code == 200 or response.status_code == 201:
            if response.json()['message'].lower() == 'ok':
                return True
        return False
    except Exception as ex:
        divide_line()
        print('Could not reach ' + url)
        print(ex)
Exemplo n.º 11
0
def main_ui(auth_header):
    divide_line()
    print('Welcome to the Main UI.')
    print()
    print('1: Quests')
    print('2: Taverna')
    print('3: Users')
    print('4: Map')
    print('5: Mutex')
    print('6: Logout')
    print('else to exit')
    return main_filter(input('\nWhere do you want to go \n> '), auth_header)
Exemplo n.º 12
0
def user_interaction_ui(auth_header, response_json, user_url):
    divide_line()
    print('So we found this adventurer here ' + user_url)
    print('But what do we do with him?')
    print()
    print('1: Send a message.')
    print('2: Join group')
    print('3: Hire')
    print('4: Inspect group')
    print('5: Send assignment')
    print()
    return user_interaction_filter(input('Boss? \n> '), auth_header,
                                   response_json, user_url)
Exemplo n.º 13
0
def visit_northern_wilds(auth_header, quest_host, location_url):
    divide_line()
    print('We arrived at {0}{1}. Lets see what where we can help!'.format(
        quest_host, location_url))
    visit_resp = requests.get('http://' + quest_host + location_url,
                              headers=auth_header)
    print(visit_resp.json())
    print()
    print('Message: ' + str(visit_resp.json()['message']))
    if visit_resp.json().get('next'):
        visit_northern_wilds(auth_header, quest_host,
                             visit_resp.json().get('next'))
    if visit_resp.json().get('critical_section'):
        print('Such wow, critical section')
Exemplo n.º 14
0
def taverna(auth_header):
    # Entering the Taverna
    divide_line()
    print('So you are a juggernaut huh? And I can reach you at ' + get_config()[util_own_server] + '? Weird address, well have fun.')
    print( get_config()[util_own_server])
    adventurer_data = json.dumps({"heroclass":"space_ninja","capabilities": str(get_config()[util_req]),"url": get_config()[util_own_server]})
    taverna_enter_resp = requests.post(paths_util.adventurers_uri(), headers=auth_header, data=adventurer_data)
    print(('System: ' + taverna_enter_resp.json()['message']))
    print('\nYou enter the dusty taverna')
    in_taverna = True
    while in_taverna:
        divide_line()
        in_taverna = taverna_ui(auth_header)
    print('Leaving the taverna')
Exemplo n.º 15
0
def look_at_map(auth_header):
    print()
    print('Lets look at our map')
    map_resp = requests.get(get_config()['server'] + get_config()['map_url'],
                            headers=auth_header)
    print()
    if map_resp.json()['status'] == 'success':
        print('Map: \n')
        for location in map_resp.json().get('objects'):
            print('Name:     ' + location['name'])
            print('Host:     ' + location['host'])
            print('Tasks:    ' + str(location['tasks']))
            print('Visitors: ' + str(location['visitors']))
            divide_line()
    print()
    return
Exemplo n.º 16
0
def create_group(auth_header, groups):
    divide_line()
    create_new = False
    if get_config()[util_group] != '':
        print('You are already in a group! ' + str(get_config()[util_group]))
        create = input('Do you really want to create another one? [y]\n> ')
        if create == 'y':
            create_new = True
    else:
        create_new = True
    if create_new:
        response = requests.post(paths_util.group_url(), headers=auth_header)
        change_config(util_group,
                      response.json()['object'][0]['_links']['self'])
        print(response.json()['message'])
    show_all_groups(auth_header, groups)
    divide_line()
    join = input('Well you founded it... You want in? [y]\n> ')
    if join == 'y':
        join_group(auth_header, groups)
Exemplo n.º 17
0
def leave_group(auth_header, groups):
    divide_line()
    print('The groups you are in:')
    groups_you_are_in = []
    for k, v in groups.items():
        if v['owner'] == get_config()[util_user]:
            groups_you_are_in.append(v)
    print(groups_you_are_in)
    divide_line()
    group_id = input('Which group do you want to leave then? [a valid id]\n> ')
    group_existant = False
    if group_id in groups:
        group_existant = True
    if group_existant:
        response = requests.post(paths_util.group_url_id(group_id) +
                                 get_config()['member_url'],
                                 headers=auth_header)
        print(response.json())
        print('Joined Group')
    else:
        print('The group with this id does not exist')
Exemplo n.º 18
0
    def post(self):
        try:
            json_data = request.get_json(force=True)
            if bool(json_data) and len(json_data) == 7:
                assignment_data = {
                    "id": str(json_data['id']),
                    "task": str(json_data['task']),
                    "resource": str(json_data['resource']),
                    "method": str(json_data['method']),
                    "data": str(json_data['data']),
                    "user": str(json_data['user']),
                    "message": str(json_data['message'])
                }
                change_config(util_assignments, assignment_data)
                divide_line()
                print('Callback:')
                print('Received finished assignment: ' + str(assignment_data))
                add_to(util_recv_tokens, str(json_data['data']['token']))
                divide_line()
                print(get_config()[util_recv_tokens])
                divide_line()

                return jsonify(message="thats all")
            else:
                return abort(400)
        except KeyError or TypeError:
            return abort(400)
Exemplo n.º 19
0
def election_algorithm(election_data):
    data = json.dumps(election_data)
    response = requests.get(get_config()[util_group] +
                            get_config()['member_url'],
                            headers=get_config()[auth_token])
    coordinator = True
    pool = ThreadPool(processes=3)
    for member in response.json()['objects']:
        if member['user'] > ('/users/' + get_config()[util_user]):
            print(member['user'])
            print('/users/' + get_config()[util_user])
            print(member['user'] > '/users/' + get_config()[util_user])
            if make_http(member['url']) != get_config()[util_own_server]:
                try:
                    user = requests.get(make_http(member['url']))
                    async_result = pool.apply_async(
                        recv_ok,
                        (make_http(member['url']) + user.json()['election'],
                         data))
                    if async_result.get():
                        coordinator = False
                except Exception as ex:
                    print('Could not reach - ' + str(member['user']))
                    print(ex)
    if coordinator:
        divide_line()
        print('Heroy is president!')
        if input('Solve the assginment?\n> ') == 'y':
            ok = solve_assignment(election_data['job'], election_data['user'])
            if not ok:
                print('Could not finish our assignment!')
        else:
            election_algorithm(election_data)
    else:
        divide_line()
        print(
            'What?! We were not elected? Change our name to "zzzz" immediatly!'
        )
Exemplo n.º 20
0
def show_adventurers(auth_header):
    response = requests.get(paths_util.adventurers_uri(), headers=auth_header)
    adventurers = {}
    divide_line()
    for idx, adventurer in enumerate(response.json()['objects']):
        adventurers[str(idx)] = adventurer
        print(str(idx) + ': ', end='')
        if adventurer.get('heroclass'):
            print(adventurer.get('heroclass') + ' | ', end='')
        if adventurer.get('user',''):
            print(adventurer.get('user') + ' | ', end='')
        if adventurer.get('capabilities'):
            print(adventurer.get('capabilities') + ' | ', end='')
        if adventurer.get('url'):
            print(adventurer.get('url'), end='')
        print()
    divide_line()

    if get_config()[util_group] != '':
        recruit = input('Want to recruit one of these guys? [id,id,id]\n> ')
        to_hire = recruit.split(',')
        for id in to_hire:
            hire_adventurer(auth_header, adventurer=adventurers[id])
Exemplo n.º 21
0
def visit_wounded(auth_header, quest_host, location_url):
    divide_line()
    print('We arrived at {0}{1}. Lets see what where we can help!'.format(
        quest_host, location_url))
    visit_resp = requests.get('http://' + quest_host + location_url,
                              headers=auth_header)
    print(visit_resp.json())
    print()
    print('Message: ' + str(visit_resp.json()['message']))
    tokens = []
    if visit_resp.json().get('steps_todo'):
        change_config(util_recv_tokens, [])
        print('Next Steps: ' + str(visit_resp.json().get('steps_todo')))
        for step in visit_resp.json()['steps_todo']:
            step_result = visit_wounded(auth_header, quest_host, step)
            if step_result:
                tokens.append(step_result)
        divide_line()
        for tk in get_config()[util_recv_tokens]:
            tokens.append(tk)
        input('Received all tokens?')
        tokens_string = '['
        for idx, token in enumerate(tokens):
            if idx == len(tokens) - 1:
                tokens_string += '"' + token + '"]'
            else:
                tokens_string += '"' + token + '",'
        data = '{"tokens":' + tokens_string + '}'
        quest_resp = requests.post('http://' + quest_host + location_url,
                                   headers=auth_header,
                                   data=data)
        print(quest_resp)
        print(quest_resp.json())
        token = quest_resp.json()['token']
    else:
        divide_line()
        send_as = input('Send as an assignment? [y]\n> ')
        if send_as == 'y':
            send_assignment_to_group(
                auth_header,
                '',
                id=2,
                task='4',
                resource=quest_host + location_url,
                task_data='',
                method='POST',
                message=
                'Help me with Quest 3 please! Send me the token to callback :)'
            )
            return False
        else:
            post_to = requests.post('http://' + quest_host + location_url,
                                    headers=auth_header)
            print('Aquired Token! ' + post_to.json()['token_name'])
            return post_to.json()['token']
    return token
Exemplo n.º 22
0
def get_adventurer(auth_header, name):
    response = requests.get(paths_util.adventurer_uri_name(name), headers=auth_header)
    divide_line()
    if response.status_code == 200 or response.status_code == 201:
        print('\nThe User: '******'object']['url'].startswith('http://'):
            user_url = 'http://' + response.json()['object']['url']
        else:
            user_url = response.json()['url'][0:response.json()['url'].find('/')]
        try:
            user_info = requests.get(user_url)
            if user_url[-1] == '/':
                user_url = user_url[:-1]
            print('User:           '******'user']))
            print('Messages:       ' + str(user_info.json()['messages']))
            print('Idle:           ' + str(user_info.json()['idle']))
            print('Group:          ' + str(user_info.json()['group']))
            print('Hiring:         ' + str(user_info.json()['hirings']))
            print('Assignments:    ' + str(user_info.json()['assignments']))
            return user_interaction_ui(auth_header, user_info.json(), user_url)
        except Exception:
            print('Connection Refused. Does not want to talk it seems :/')
    else:
        print('Could not connect to user')
Exemplo n.º 23
0
def main():
    divide_line()
    change_config(util_req, [])
    add_to(util_req, 'election-algorithm')
    add_to(util_req, 'mutex')
    set_own_url()
    if get_config()['server'] != '':
        research = input(
            'Do you want to re-search for the blackboard host? [y] \n> ')
        if research == 'y':
            set_server_url_via_udp()
    else:
        set_server_url_via_udp()

    # Authentication
    do_it_yourself, already_logged = False, False
    divide_line()
    print('Authentication')
    if get_config().get(token) != '':
        print('- You are already logged in!')
        print()
        hand_login = input('Still... Do you want to login yourself? [y]\n> ')
        if hand_login == 'y':
            do_it_yourself = True
        else:
            already_logged = True
            auth_header = get_config()[token]
            whoami(auth_header)
            divide_line()
    if do_it_yourself or not already_logged:
        user_authenticated = False
        while not user_authenticated:
            exit, auth_header = authentication()
            exit_check(exit)
            user_authenticated = whoami(auth_header)
        print()
    if get_config()[util_group] != '':
        if not util_group in get_config()[util_req]:
            add_to(util_req, util_group)
            print('Added "Group" to capabilities!\n')
    print('Authentication Token: ' + str(auth_header))
    print()
    print('Online at: ' + get_config()[util_own_server])
    divide_line()
    while True:
        main_ui(auth_header)
Exemplo n.º 24
0
def whoami(auth_header):
    divide_line()
    whoami_resp = requests.get(get_config()['server'] +
                               get_config()['whoami_url'],
                               headers=auth_header)
    if whoami_resp.json().get('user'):
        show = input('Show user info? [y/n] \n> ')
        if show == 'y' or show == 'yes':
            print('## WhoAmI ##\n' + 'Name: ' +
                  str(whoami_resp.json()['user']['name']) + '\n' +
                  'Finished deliverables: ' +
                  str(whoami_resp.json()['user']['deliverables_done']) + '\n' +
                  'Delivered: ' + str(whoami_resp.json()['user']['delivered']))
            print(whoami_resp.json().get('message'))
            divide_line()
        else:
            print('Not showing user info')
        return True
    else:
        print('!!! You could not be authenticated. Please try again !!!')
        divide_line()
        return False
Exemplo n.º 25
0
def visit_elves(auth_header, quest_host, location_url):
    divide_line()
    visit_resp = requests.get('http://' + quest_host + location_url,
                              headers=auth_header)
    print(visit_resp.json()['message'])
    divide_line()
    assignment_data = {
        "id": 300000,
        "task": '/blackboard/tasks/7',
        "resource": (quest_host + location_url),
        "method": 'POST',
        "data": {
            "group": get_config()[util_group]
        },
        "callback": get_config()['callback_url'],
        "message": 'Help! Save the elves! Put on the ring!'
    }
    change_config(util_recv_tokens, [])
    start_election(job_data=assignment_data)
    divide_line()
    input('Did you get back the election result? Should have callbacked!\n> ')
    return get_config()[util_recv_tokens]
    '''
Exemplo n.º 26
0
def send_assignment_to_group(auth_header,
                             _,
                             id=None,
                             task=None,
                             resource=None,
                             method=None,
                             task_data=None,
                             message=None,
                             answers_needed=1):
    answers = 0
    if get_config()[util_group] != '':
        if not id:
            id = input('ID:         ')
        if not task:
            task = input('Tasknumber: ')
        if not resource:
            resource = input('Resource:   ')
        if not method:
            method = input('Method:     ')
        if not task_data:
            task_data = input('Data:       ')
            if not task_data:
                task_data = ''
        if not message:
            message = input('Message:    ')

        response = requests.get(get_config()[util_group] +
                                get_config()['member_url'],
                                headers=auth_header)
        if not response.status_code == 200 or response.status_code == 201:
            print()
            print('Could not get the members of your group')
            divide_line()
        else:
            data = json.dumps({
                "id":
                str(id),
                "task":
                get_config()['blackboard_url'] + get_config()['task_url'] +
                task,
                "resource":
                str(resource),
                "method":
                str(method),
                "data":
                str(task_data),
                "callback":
                get_config()['callback_url'],
                "message":
                str(message)
            })
            print('Sending assignment: ' + str(data) + ' to group members')
            for member in response.json()['objects']:
                if not paths_util.make_http(member['url']) == str(
                        get_config()[util_own_server]):
                    try:
                        member_url = paths_util.make_http(member['url'])
                        print('Sending assignment to: ' + str(member_url))
                        member_data = requests.get(member_url)
                        if member_data and (member_data.status_code == 200
                                            or member_data.status_code == 201):
                            user_url = paths_util.make_http(member['url'])
                            try:
                                response = requests.post(
                                    user_url +
                                    member_data.json()['assignments'],
                                    data=data)
                                if response.status_code == 200:
                                    print('Assignment sent to ' +
                                          str(member['user']))
                                    answers += 1
                                    if answers_needed == answers:
                                        print('Send all')
                                        return
                            except Exception as ex:
                                print('Member: ' + str(member['user']) +
                                      ' could not be reached')
                                print(ex)
                                print()
                        else:
                            print('Member URL could not be reached!')
                    except Exception as ex:
                        print('Member ' + str(member['user']) +
                              ' could not be reached\n-> Reason:\n')
                        print(ex)
                        print()
                else:
                    print('Skipping mighty me!')
Exemplo n.º 27
0
def request_mutex():
    config = get_config()
    if config['state'] == 'wanting' or config['state'] == 'held':
        print('Already in a state of "wanting" or "held"')
        released =input('Change to released? [y]\n> ')
        if released == 'y':
            change_config('state', 'released')

    if config['state'] != 'wanting' or config['state'] != 'held':
        print('Sending requests to all adventureres')
        change_config('state','wanting')
        adventureres = get_all_adventureres()
        for idx, adventurer in enumerate(adventureres):
            try:
                if 'mutex' in adventurer['capabilities']:
                    response = requests.get(make_http(adventurer['url']), timeout=5)
                    adventurer_mutex_endpoint = response.json()['mutex']
                    data_json = json.dumps({
                        "msg": "request",
                        "time": get_config()['lamport_clock'],
                        "reply": config['own_address'] + config['mutex_url'],
                        "user": config['own_address'] + config['hero_url']
                    })
                    try:
                        response = requests.post(make_http(adventurer['url'] + adventurer_mutex_endpoint), data=data_json, timeout=5)
                        print('Posted mutex request to ' + str(adventurer['url'] + adventurer_mutex_endpoint))
                        change_config('lamport_clock', get_config()['lamport_clock'] + 1)
                        print(str(response.json()))
                        if not response.json().get('msg'):
                            add_to('waiting_answers', adventurer['user'])
                        else:
                            if not response.json().get('msg')== 'reply-ok':
                                add_to('waiting_answers', adventurer['user'])
                    except Exception as e:
                        print('Something is wrong! Just wrong: \n' + str(e))
                else:
                    print('Adventurer ' + str(idx) + ' is not worthy!')
            except Exception as e:
                print('Adventurer ' + str(idx) + ' with url ' + str(adventurer['url']) + ' could not be reached')
                print('But our messenger told us: ' + str(e))

        divide_line()
        tries = 0
        trymax = len(get_config()['waiting_answers'])
        while len(get_config()['waiting_answers']) != 0 and tries <= trymax:
            print('Waiting for ' + str(len(get_config()['waiting_answers'])) + ' answers')
            time.sleep(1)
            if tries == trymax:
                print('Did not receive all answers :C. Still entering critial_section')
            tries += 1
        divide_line()
        change_config('lampock_clock', 0)
        change_config('waiting_answers', [])
        print('Entering the critical area')
        change_config('state', 'held')
        time.sleep(3)
        try:
            requests.put(make_http(config['own_address'] + config['mutex_url']), data=json.dumps({"message":"release the kraken"}))
        except Exception as e:
            print('Put the kraken error: ' + str(e))
        print('Leaving the critical section')
        change_config('state', 'released')
        divide_line()
Exemplo n.º 28
0
def change_adventurer(auth_header, name):
    response = requests.put(paths_util.adventurer_uri_name(name), headers=auth_header)
    print(response)
    divide_line()
Exemplo n.º 29
0
def solve_assignment(json_data, sender_uri):
    change_config(util_assignments, json_data)

    divide_line()
    print('Received assignment: \n' + str(json_data['message']) + '\n' +
          str(json_data['method']) + '\n' + str(json_data['resource']))

    url = paths_util.make_http(json_data['resource'])
    if json_data['method'].lower() == 'get':
        response = requests.get(url,
                                headers=get_config()[auth_token],
                                data=json.dumps(json_data['data']))
    elif json_data['method'].lower() == 'post':
        response = requests.post(url,
                                 headers=get_config()[auth_token],
                                 data=json.dumps(json_data['data']))
    else:
        return False

    print('Response of method:')
    print(response.json()['message'])
    print(response.status_code)
    print()
    if response.status_code == 200:
        print(response.json()['message'])
        divide_line()
        new_assignment = {
            "id": json_data['id'],
            "task": json_data['task'],
            "resource": json_data['resource'],
            "method": json_data['method'],
            "data": {
                "group": get_config()[util_group],
                "token": response.json()['token']
            },
            "callback": json_data['callback'],
            "message": "Oh no, i am unconcious, take over please!"
        }
        if response.json().get('hint'):
            print(response.json()['hint'])
            input('Everyone ready?')
            print('Starting new election')
            if sender_uri:
                start_election(job_data=new_assignment, user=sender_uri)
            else:
                start_election(job_data=new_assignment)

    answer = json.dumps({
        'id':
        json_data['id'],
        'task':
        json_data['task'],
        'resource':
        json_data['resource'],
        'method':
        json_data['method'],
        'data':
        response.json(),
        'user':
        get_config()['username'],
        'message':
        'Swifty swooty as ever has Heroy done his job.'
    })

    print(sender_uri)
    print(json_data['callback'])

    callback_address = paths_util.make_http(
        port_check(sender_uri) + json_data['callback'])
    print('That went well, answering to Callback! ' + str(callback_address))
    try:
        callback_resp = requests.post(callback_address, data=answer)
        if callback_resp.status_code == 200 or callback_resp.status_code == 201:
            divide_line()
            print('Callback sent successfully')
        else:
            print('Could not reach callback url')
            divide_line()
    except Exception as cre:
        print('Could not reach callback, Connection Refused!')
        print(cre)
Exemplo n.º 30
0
def kill_adventurer(auth_header, name):
    response = requests.delete(paths_util.adventurer_uri_name(name), headers=auth_header)
    print(response)
    divide_line()