def join_session(): session = sessions.get_session(request.form["session_id"]) if session is None: # session doesn't exists return redirect(url_for("get_active_sessions")) if not session["active"]: # session is closed return redirect(url_for("get_active_sessions")) flask_session["active_session"] = request.form["session_id"] return redirect(url_for("get_pizzaorder"))
def index(): db = get_db() (sessionID, google_account, set_cookie) = sessions.get_session(db, lambda key: request.cookies.get(key), ["google_account"]) retval = render_template("index.html", sessionID=sessionID, mail=google_account) if set_cookie: retval.set_cookie("sessionID", sessionID) return retval
def ugly(gameID, halfmoveNum): try: db = get_db() (sessionID, google_account, set_cookie) = sessions.get_session( db, lambda key: request.cookies.get(key), ["google_account"]) try: vals = get_game_info(db, gameID) wh = vals["white"] bl = vals["black"] except TC_IDNotFoundError: TODO history = get_moves(db, gameID) max_move = len(history) - 1 history_display = "" for i in range(1, len(history), 2): history_display += "{:2d}. ".format(i / 2 + 1) pair = history[i:i + 2] if len(pair) == 2: history_display += "{:8s}{}".format(*pair) else: history_display += pair[0] history_display += "\n" history_display = history_display[:-1] if len(history) - 1 < halfmoveNum: TODO if max_move > halfmoveNum: history = history[:halfmoveNum + 1] game = build_board_from_move_list(history) legal_moves = sorted(game.legal_moves_san()) return render_template("ugly.html", board=game.get_simple_drawing(), history=history_display, legal_moves=legal_moves, gameID=gameID, halfmoveNum=halfmoveNum, max_move=max_move) except TC_DBImpossibleError: TODO
def __init__(self, profile, account_number, stage, deployment_type, dry_run): self.profile = profile self.account_number = account_number self.dry_run = dry_run if deployment_type == "jenkins": self.session = get_session(account_number, "TDRTerraformRole" + stage.capitalize()) else: self.session = boto3.session.Session(profile_name=self.profile) self.client = self.session.client('iam') aliases = self.client.list_account_aliases()['AccountAliases'] #print(json.dumps(aliases, sort_keys=True, indent=2, default=json_serial)) print('Deleting VPCs in Account %s' % aliases[0])
def game(gameID, halfMoveNum): db = get_db() (sessionID, google_account, set_cookie) = sessions.get_session(db, lambda key: request.cookies.get(key), ["google_account"]) # TODO: confirm that the game ID is valid. Or should this be a function # of the Javascript code??? history = ["e4", "e5", "Ng3", "Nc6"] game = TimeChess_Game() game.add_to_history("e4") game.add_to_history("e5") legal_moves = sorted(game.legal_moves_san()) def piece_url(sym): color = 'l' if sym.isupper() else 'd' kind = sym.lower() path = "board_images/{}{}t60.png".format(kind, color) return url_for("static", filename=path) pieces = [(piece_url(sym), x, y) for (x, y, sym) in game.piece_list_xy()] retval = make_response( render_template("game.html", gameID=gameID, history=history, halfMoveNum=halfMoveNum, legal_moves=legal_moves, board=str(game.board), pieces=pieces)) if set_cookie: retval.set_cookie("sessionID", sessionID) return retval
import sys from sessions import get_session account_number = sys.argv[1] stage = sys.argv[2] service_name = sys.argv[3] boto3_session = get_session(account_number, 'TDRJenkinsECSUpdateRole' + stage.capitalize()) client = boto3_session.client('ecs') resp = client.update_service(cluster=service_name + '_' + stage, service=service_name + '_service_' + stage, forceNewDeployment=True) print(resp['service']['serviceArn'])
import sys from sessions import get_session account_number = sys.argv[1] stage = sys.argv[2] instance_name = sys.argv[3] command_name = sys.argv[4] boto_session = get_session(account_number, "TDRJenkinsRunDocumentRole" + stage.capitalize()) client = boto_session.client('ssm', region_name='eu-west-2') parameter = client.send_command(Targets=[{'Key': 'tag:Name','Values': [instance_name]}], DocumentName=command_name) print("Command " + command_name + "has been run on instance " + instance_name)
def __init__(self, profile, account_number, stage, deployment_type, dry_run): self.profile = profile self.account_number = account_number self.dry_run = dry_run if deployment_type == "jenkins": self.session = get_session(account_number, "TDRTerraformRole" + stage.capitalize()) else: self.session = boto3.session.Session(profile_name=self.profile) self.client = self.session.client('ec2') print("Retrieving all AWS regions") regions = self.client.describe_regions()['Regions'] #print('Regions:', regions) for region in regions: self.client = self.session.client('ec2', region_name=region['RegionName']) print("Searching for ec2 resources in region %s" % region['RegionName']) igs = self.client.describe_internet_gateways()['InternetGateways'] vpcs = self.client.describe_vpcs()['Vpcs'] #print(json.dumps(vpcs, sort_keys=True, indent=2, default=json_serial)) for vpc in vpcs: if vpc['IsDefault']: acls = self.client.describe_network_acls( Filters=[{ 'Name': 'vpc-id', 'Values': [vpc['VpcId']] }])['NetworkAcls'] for acl in acls: if acl['IsDefault'] != True: print("Deleting network acl %s" % acl['NetworkAclId']) if self.dry_run is None: self.client.delete_network_acl( NetworkAclId=acl['NetworkAclId']) sgs = self.client.describe_security_groups( Filters=[{ 'Name': 'vpc-id', 'Values': [vpc['VpcId']] }])['SecurityGroups'] for sg in sgs: if sg['GroupName'] != 'default': #print("==========") #print(json.dumps(sg, sort_keys=True, indent=2, default=json_serial)) #print("==========") print("Deleting sg %s" % sg['GroupName']) if self.dry_run is None: for i in xrange(0, 20): try: self.client.delete_security_group( GroupId=sg['GroupId']) print("deleted %s" % sg['GroupName']) break except ClientError as e: print("retrying: (error: %s)" % e) time.sleep(10) continue for ig in igs: for att in ig['Attachments']: if att['VpcId'] == vpc['VpcId']: print("Deleting ig %s" % ig['InternetGatewayId']) if self.dry_run is None: self.client.detach_internet_gateway( InternetGatewayId=ig[ 'InternetGatewayId'], VpcId=vpc['VpcId']) self.client.delete_internet_gateway( InternetGatewayId=ig[ 'InternetGatewayId']) subnets = self.client.describe_subnets( Filters=[{ 'Name': 'vpc-id', 'Values': [vpc['VpcId']] }])['Subnets'] for subnet in subnets: print("Deleting subnet %s" % subnet['SubnetId']) #print(json.dumps(subnet, sort_keys=True, indent=2, default=json_serial)) if self.dry_run is None: self.client.delete_subnet( SubnetId=subnet['SubnetId']) for vpc in vpcs: if vpc['IsDefault']: print("Deleting vpc %s" % vpc['VpcId']) if self.dry_run is None: self.client.delete_vpc(VpcId=vpc['VpcId']) print("deleted %s" % vpc['VpcId'])
def move_helper(vars): db = get_db() (sessionID, google_account, set_cookie) = sessions.get_session(db, lambda key: request.cookies.get(key), ["google_account"]) # TODO: move the '++' suffix out of the 'moves' table, and add a 'status' field to games. This will allow us to check, trivially, if one side or the other has won, which will simplify a lot of checks. # did they pass the required variables? if "gameID" not in vars or "hmNum" not in vars or "move" not in vars: TODO gameID = int(vars["gameID"]) halfMoveNum = int(vars["hmNum"]) newMove = vars["move"] if gameID <= 0 or halfMoveNum <= 0 or len(newMove) == 0: TODO # is the current logged-in person a player on the site? cursor = db.cursor() cursor.execute( "SELECT players.id FROM sessions,players WHERE sessions.sessionID=%s AND players.google_account=sessions.google_account", (sessionID, )) rows = cursor.fetchall() cursor.close() if len(rows) != 1: TODO playerID = rows[0][0] # get basic game info. Only a player in the game can play, and they can # only choose their own moves. cursor = db.cursor() cursor.execute("SELECT white,black FROM games WHERE id=%s", (gameID, )) rows = cursor.fetchall() cursor.close() if len(rows) != 1: TODO wh, bl = rows[0] assert wh != bl # is the player not in the game? if playerID not in (wh, bl): TODO # is it even this player's turn? If they were the last player to play # in the past, then they cannot play again, until the other side plays. # TODO # is the player attempting to move for the other side? if playerID == wh: if halfMoveNum % 2 != 1: pass # TODO else: if halfMoveNum % 2 != 0: pass # TODO # get the list of moves from the database. This will report only a # *single* move for each halfMoveNum (the most recent one), but it will # include the seqNum for each, since that is useful later. Note that this # is only a DB search; it does *NOT* know which of these moves might be # invalidated. This does *NOT* look for checkmate anywhere - it returns # the *entire* history, even if there is a checkmate in the middle. # # Also note that the first element is always None, so that the first # halfMove - numbered 1 for user convenience - will be in slot [1] of the # returned list. Thus, an empty list is invalid, but a list with only one # element is valid; that simply means that the game has no moves. (If you # ask it for an invalid game ID, this is what you will get - it does *NOT* # validate that the gameID is valid. But that's no worry in this code, # since we validated the gameID above.) # # Note that each element (save the None in [0]) is a tuple: (move,seqNum) moves = get_moves(db, gameID, include_seqNum=True) # is the move too advanced - no connection to it in the history? if halfMoveNum > len(moves): TODO # is there already a checkmate, anywhere in the move list? Or any # end-of-game marker at all? # TODO: handle game-state, which is now in the 'games' table # SIMPLE CASE: Brand-new move if halfMoveNum == len(moves): seqNum = 1 # TODO: In this case, if the last move (by the other guy) was a # Pending, then we need to convert it to a Pass. else: # TODO: In this case, if the last move (by me) was a Pending, we can # replace it. If the last move (by the other guy) was a Pending, # then we should remove that from the move order, in addition # to adding our new one. On the other hand, if the last move by # the other guy was *NOT* a Pending, then we must *add* a Pending # to the end of our move list (in addition to changing the past) # have we already had too many alterations to that move (our DB table can # only hold seqNums up to 9). Note that this is also useful, even if the # user is not doing anything bad, since we'll need to *set* the seqNum in # the new row we insert soon. assert type( moves[halfMoveNum][1]) == int # did we remember to convert it? if moves[halfMoveNum][1] == 9: TODO # is the move in question a "Pass"? If so, then the player has lost the # chance to move, and can never change it. if moves[halfMoveNum][0] == "Pass": TODO seqNum = moves[halfMoveNum][1] + 1 # looks like (hopefully) we're going to add an update to the database. To # ensure that this is a legal move (and to check for checkmate as a result # of this new move), we need to build a Board object which represents the # current state (as of the position where we're making a change). moves_no_seqNums = [None] + [m[0] for m in moves[1:]] board = build_board_from_move_list(moves_no_seqNums[:halfMoveNum]) # check to see if the move is legal, given the history that comes # before it in the game. if not board.move_is_legal(newMove): TODO # apply the move, and check for checkmate. board.apply_move(newMove) if board.is_game_over(): TODO # all looks good. Record the new move into the DB. (Note the cool SQL # nested query, to set the debug_seq field...this is a new thing for me to # try out, and I sure hope I get it right!) - Russ, 26 Jun 2020 cursor = db.cursor() cursor.execute( """INSERT INTO moves(gameID,halfMoveNum,seqNum,move,debug_seq) SELECT %s,%s,%s,%s, 1+MAX(debug_seq) FROM moves WHERE gameID=gameID""", (gameID, halfMoveNum, seqNum, newMove)) if cursor.rowcount != 1: TODO cursor.close() # yay, all done! db.commit() # TODO: wake up Redis server, let it know that a new move has happened. retval = redirect(url_for("ugly", gameID=gameID, halfmoveNum=halfMoveNum)) if set_cookie: retval.set_cookie("sessionID", sessionID) return retval
import sys from sessions import get_session account_number = sys.argv[1] stage = sys.argv[2] function_name = sys.argv[3] version = sys.argv[4] function_arn = f'arn:aws:lambda:eu-west-2:{account_number}:function:{function_name}' boto_session = get_session(account_number, "TDRJenkinsLambdaRole" + stage.capitalize()) client = boto_session.client("lambda") event_mappings = client.list_event_source_mappings()['EventSourceMappings'] uuid = list( filter(lambda x: x['FunctionArn'].startswith(function_arn), event_mappings))[0]['UUID'] client.update_event_source_mapping(UUID=uuid, FunctionName=function_arn + ":" + version)
def session_dashboard(): session_id = flask_session["active_session"] session_data = sessions.get_session(session_id) return render_template("session_dashboard.jinja", orders=session_data["orders"])
import sys from sessions import get_session # This script will retrieve the SSM param and prints the value # To ensure the value does not appear in the console run the script with set+x command this will hide the output on the console: # sh """ # set +x # [command that uses script] # """ account_number = sys.argv[1] stage = sys.argv[2] param_name = sys.argv[3] boto_session = get_session(account_number, "TDRJenkinsReadParamsRole" + stage.capitalize()) client = boto_session.client('ssm', region_name='eu-west-2') parameter = client.get_parameters(Names=[param_name], WithDecryption=True) print(parameter['Parameters'][0]['Value'])
def __handle(self): sess_token = None try: print "Client connected from %s:%d" % (self.__client_address) self.__client_socket.send(pickle.dumps(self.sess_names, -1)) #self.__client_socket.send(DELIM.join([ x for x in self.sess_names])) initial_reply = self.__client_socket.recv(self.buffer_size) print initial_reply initial_reply = initial_reply.split(DELIM) nick = "" print initial_reply if initial_reply[0] == NEW_SESSION: nick = initial_reply[3] print 'Creating new session' print 'initial_reply[2] ', initial_reply[2] ''' creating new session using function !!! do not use class creation !!!! ''' sess = new_session(self.__client_address, int(initial_reply[2]), initial_reply[1]) #print "ebu4iy token ", t # self.cv_sess.notify() print "Session ", sess.get_name(), " created with token ", sess.get_token() sess.add_player(nick, self.__client_socket) #self.__client_socket.send(sess.get_token()) #sess.add_player(nick, self.__client_socket) #self.__client_socket.send(sess.get_token()) #self.cv_sess.notify() #save_session(self.cv_sess) if initial_reply[0] == OLD_SESSION: name = initial_reply[1] print "find session by name ", name sess = get_session(name) #get_session(initilal_reply[1]) nick = initial_reply[2] print "Player ", nick, " connected to session ", sess.get_token() sess.add_player(nick, self.__client_socket) #self.__client_socket.send(sess.get_token()) # if he created new session 0 - sess = Game_Session() # call function gamesession to add client name first time game_session new_player_in_current_session #print "Client's nickname=", nick with lc_message: self.__client_socket.send(sess.get_token()) while True: if sess.get_status() == True: ''' with lc_message: print "send client ", GAME_START self.__client_socket.send(GAME_START) ''' break print "game loading..." time.sleep(10) #print "send token ", sess_token #self.__client_socket.send(sess_token) while True: print "awaiting data" resp = self.__client_socket.recv(self.buffer_size) resp = resp.split(DELIM) print resp if resp[0] == PLAY_TURN: cell = (resp[1], resp[2]) value = resp[3] sess.play_turn(cell, value, nick) if resp[0] == UPDATE_GAME: continue if resp[0] == DISCONNECT: break #receive answer from client: (i,j) 8 #game_session solver(name, client_answer) - there check if it solved if yes return message #time.sleep(1) #send table_score to client and/or message except soc_err as e: if e.errno == 107: print "Client left befor handle" else: print "error %s" % str(e) except: print "Some error occured!" self.__client_socket.close() finally: self.__client_socket.close() if not sess == None: print "HANDLER REMOVE PLAYER ", nick sess.remove_player(nick, self.__client_socket) print "client disconected"