def enter_critical_section(): config = get_config() own_address = config['own_address'] lamport_clock = config['lamport_clock'] waiting_answers = config['waiting_answers'] request = { "msg": "request", "time": lamport_clock, } requests.post('http://' + str(own_address) + ':' + str(5000), data=request) state = {"message": "state", "state": "wanting"} requests.put('http://' + str(own_address) + ':' + str(5000), data=state) # Adventurers list kriegen # nötigen Informationen ip addresse + mutex-uri adventurers = list() for adventurer in adventurers: # request an den adventurer/mutex senden # wenn der nicht mit reply-ok antwortet # füge die ip addresse in waiting_answers lamport_clock += 1 change_config('waiting_answers', waiting_answers) change_config('lamport_clock', lamport_clock) while len(waiting_answers) > 0: waiting_answers = get_config()['waiting_answers'] state["state"] = "held" requests.put('http://' + str(own_address) + ':' + str(5000), data=state) # do something state["state"] = "released" requests.put('http://' + str(own_address) + ':' + str(5000), data=state)
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)
def post(self): json_data = request.get_json(force=True) config = get_config() group = config['group'] try: message = 'Mighty Heroy Jenkins does not take your pity quest' status_code = 418 take_quest = '' while take_quest != 'y' and take_quest != 'n': take_quest = input( "Do you want to take part in the quest: {0} of the group {1}? Message: {2}. If you do, you will " "leave your current group and join theirs Answer with [y,n]" .format(json_data['quest'], json_data['group'], json_data['message'])) if take_quest == 'n': break elif take_quest == "y": message = 'I\'m in the fun' status_code = 200 print(json_data['group']) #post_join_group(group_id) change_config('group', json_data['group']) break return jsonify({'message': message}), status_code except KeyError or TypeError: return abort(400)
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
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)
def put(self): json_data = request.get_json(force=True) try: if json_data['message'] == 'release the kraken' and len( json_data) == 1: config = get_config() lamport_clock = config['lamport_clock'] stored_requests = config['stored_requests'] for single_request in stored_requests: response = json.dumps({ 'msg': 'reply-ok', 'time': lamport_clock, 'user': config['own_address'], 'reply': config['own_address'] + config['mutex_url'] }) try: print(single_request) response_req = requests.post(single_request, data=response) print(response_req) except Exception as e: print(str(e)) lamport_clock += 1 change_config('lamport_clock', lamport_clock) change_config('stored_requests', list()) return 200 if json_data['message'] == 'wanting' and len(json_data) == 1: change_config('state', 'wanting') return 200 if json_data['message'] == 'released' and len(json_data) == 1: change_config('state', 'released') return 200 if json_data['message'] == 'clock' and len(json_data) == 1: change_config('lamport_clock', get_config()['lamport_clock'] + 5) return 200 return abort(400) except KeyError or TypeError as e: print('Error: ' + str(e)) return abort(400)
def delete_your_group(auth_header, groups): print(paths_util.server_uri(get_config()[util_group]) + '/') response = requests.delete( paths_util.make_http(paths_util.server_uri(get_config()[util_group])) + '/', headers=auth_header) if response.status_code == 200: change_config(util_group, '') rm_from(util_req, util_group) adventurer_data = '{"heroclass":"juggernaut","capabilities":"' + str( get_config() [util_req]) + '","url":' + get_config()[util_own_server] + '}' requests.post(paths_util.adventurers_uri(), headers=auth_header, data=adventurer_data) print('Deleted your group!') else: print('Could not delete the group :C') print(response.json())
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)
def authentication(): exit = False auth_header = '' choice = authentication_ui() if choice in ['1', '2']: username = input('Username \n> ') password = input('Password \n> ') if choice == '1': user_data = '{"name":"' + username + '","password":"******"}' response = requests.post(paths_util.server_uri( get_config()['user_url']), data=user_data) print() print(response.json()['message']) change_config(util_user, username) else: change_config(util_user, username) response = requests.get(paths_util.server_uri( get_config()['login_url']), auth=(username, password)) if response.status_code == 200: print(response.json()['message']) auth_token = response.json()['token'] auth_header = {'Authorization': 'Token ' + auth_token} change_config(token, auth_header) else: exit = True return exit, auth_header
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] '''
def post_join_group(group_id): response = requests.post(paths_util.group_url_id(group_id) + get_config()['member_url'], headers=get_config()[auth_token]) print(response.json()['message'] + ' ' + str(group_id)) if response.status_code == 200 or response.status_code == 201: print('Joined Group!') group_get = requests.get(paths_util.group_url_id(group_id), headers=get_config()[auth_token]) if group_get.status_code == 200 or group_get.status_code == 201: group_url = group_get.json()['object']['_links']['self'] change_config(util_group, paths_util.server_uri(group_url)) add_to(util_req, util_group) adventurer_data = '{"heroclass":"Fantastic Space Ninja","capabilities":"' + str( get_config() [util_req]) + '","url":' + get_config()[util_own_server] + '}' requests.put(paths_util.adventurer_uri_name( get_config()['username']), headers=get_config()[auth_token], data=adventurer_data) else: print('Could not find the group. Where did they hide?!') else: print('Seems they dont want you in this group. Could not join.')
def post(self): print('Received mutex stuff') json_data = request.get_json(force=True) config = get_config() state = config['state'] lamport_clock = config['lamport_clock'] stored_requests = config['stored_requests'] waiting_answers = config['waiting_answers'] try: if json_data['msg'].lower() == 'reply-ok' and len(json_data) == 4: print('Received mutex reply-ok') if json_data['user'] in waiting_answers: print('#' * 20) print('vor dem Remove: ' + len(waiting_answers)) waiting_answers.remove(json_data['user']) print('nach dem Remove: ' + len(waiting_answers)) print('#' * 20) change_config('waiting_answers', waiting_answers) return 200 elif json_data['msg'].lower() == 'request' and len(json_data) == 4: print('Received mutex request') if state == 'released' or (state == 'wanting' and json_data['time'] >= lamport_clock): message = 'reply-ok' else: print(json_data['reply']) if json_data['reply'] not in stored_requests: stored_requests.append(json_data['reply']) message = 'request' else: return abort(400) print('Lamport') if json_data['time'] > lamport_clock: lamport_clock = json_data['time'] lamport_clock += 1 print('Response build') response = { 'msg': message, 'time': lamport_clock, 'user': config['own_address'], 'reply': config['own_address'] + config['mutex_url'] } change_config('stored_requests', stored_requests) change_config('lamport_clock', lamport_clock) print(str(response)) return jsonify(response) except KeyError or TypeError as e: print('Error working on Mutex post: ' + str(e)) return abort(400)
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)
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()