def post(self): json_data = request.get_json(force=True) config = get_config() election_data = { "algorithm": json_data['algorithm'], "payload": config[util_user], "user": json_data['user'], "job": json_data['job'], "message": "hello you there?" } print(election_data) thread = Thread(target=election_algorithm, args=(election_data, )) thread.start() return jsonify({"message": "OK"})
def send_assignment(auth_header, response_json, user_url): data = json.dumps({ "id": 9001, "task": '/blackboard/tasks/4', "resource": 'http://172.19.0.5:5000/stretcher/handle/back', "method": "POST", "data": '', "callback": get_config()['hero_url'], "message": "Do it nao xD" }) response = requests.post(user_url + response_json.get('assignments'), data=data) if response.status_code == 200 or response.status_code == 201: print(response.json()) print('Send assignment') else: print('Could not send the assignment. We are DOOOMED!')
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 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])
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!' )
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 get(self): config = get_config() response = {'state': config['state'], 'time': config['lamport_clock']} return jsonify(response)
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 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!')
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()