def get_snapshot(snapshot_id, connections, money): snapshots = [] retrieve = bank_pb2.RetrieveSnapshot() retrieve.snapshot_id = snapshot_id message = bank_pb2.BranchMessage() message.retrieve_snapshot.MergeFrom(retrieve) total = 0 print('snapshot_id: {}'.format(snapshot_id)) for sock in connections: result_str = '' # Message server message_socket(sock[0], message) # Read returned snapshot initial_data = sock[0].recv(2) data_size = struct.unpack('H', initial_data)[0] data = sock[0].recv(data_size) rec_message = bank_pb2.BranchMessage() rec_message.ParseFromString(data) assert rec_message.WhichOneof('branch_message') == 'return_snapshot' local_snapshot = rec_message.return_snapshot.local_snapshot # Get initial balance result_str += '{}: {}, '.format(sock[1], local_snapshot.balance) # if not all(x == 0 for x in local_snapshot.channel_state): # print('channel_states: ') # print(local_snapshot.channel_state) total += local_snapshot.balance for i in range(len(local_snapshot.channel_state)): if i != get_branch_index(sock[1]): amt = local_snapshot.channel_state[i] total += amt result_str += '{}->{}: {}, '.format(connections[i][1], sock[1], amt) print(result_str) print('Total: {}'.format(total)) print('') assert total == money
def __init__(self): self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.bind((socket.gethostname(), int(sys.argv[2]))) self.s.listen(100) self.branch_names = [] self.branch_ip = [] self.branch_port = [] self.balance = 0 self.mutex = Lock() self.server_branch_Message = bank_pb2.BranchMessage() self.client_branch_Message = bank_pb2.BranchMessage() self.marker_Message = bank_pb2.Marker() self.local_snapshot_Message = bank_pb2.ReturnSnapshot.LocalSnapshot() self.my_name = '' self.sock_list = [self.s] self.sock_dict = {} self.sock_dict_rev = {} self.state = [] self.rec = [] self.fm = [] self.channel_state = [] self.m_rcvd = [] self.m_rcvd_cnt = [] self.m_sent = [] self.msg_count = 0 self.map = {} self.check_branch_names = [] self.check_branch_ip = [] self.check_branch_port = []
def RetrieveSnapshot(id): time.sleep(3) #Create Retrieve Message branch_message = bank_pb2.BranchMessage() retrieve_snapshot = branch_message.retrieve_snapshot retrieve_snapshot.snapshot_id = id print "snapshot_id: ", id for b_name in branch_name: ip = branches[b_name][0] port = branches[b_name][1] s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip, int(port))) s.send(branch_message.SerializeToString()) snapshot = s.recv(100000) recv_message = bank_pb2.BranchMessage() recv_message.ParseFromString(snapshot) return_message = recv_message.return_snapshot.local_snapshot output = b_name + ": " + str(return_message.balance) + ", " output_list = [] for name in branch_name: if name != b_name: output_list.append(name + '->' + b_name) for i in range(0, len(output_list)): output = output + output_list[i] + ': ' + str( return_message.channel_state[i]) + ', ' output = output[:-2] print output s.close()
def Server(self, sock): while True: sock.listen(10) print("Server Thread Started.....!") con, ip = sock.accept() msg = bank_pb2.BranchMessage() msg.ParseFromString(con.recv(8000)) if (msg.HasField("transfer")): self.transfer(msg.transfer.money) elif (msg.HasField("init_snapshot")): print("Init Snap: {0}".format(msg.init_snapshot)) self.InitSnapshot(msg.init_snapshot.snapshot_id) elif (msg.HasField("marker")): self.marker(msg.marker) elif (msg.HasField("retrieve_snapshot")): ret = bank_pb2.BranchMessage() ret.return_snapshot.local_snapshot.snapshot_id = msg.retrieve_snapshot.snapshot_id self.mutex.acquire() if msg.retrieve_snapshot.snapshot_id not in self.snapshots: self.snapshots[msg.retrieve_snapshot.snapshot_id] = { "localState": self.balance, "incoming": [] } ret.return_snapshot.local_snapshot.balance = self.snapshots[ msg.retrieve_snapshot.snapshot_id]["localState"] # for x in self.snapshots[msg.retrieve_snapshot.snapshot_id]["incoming"]: # ch_state = ret.return_snapshot.local_snapshot.channel_state.add() # ch_state = x ret.return_snapshot.local_snapshot.channel_state.extend( self.snapshots[ msg.retrieve_snapshot.snapshot_id]["incoming"]) con.send(ret.SerializeToString()) self.mutex.release()
def retrieve_snapshot(all_branches, snapshot_id): """ Send RetrieveSnapshot message to all branches :param all_branches: List of all branches :param snapshot_id: Snapshot id """ message = bank_pb2.BranchMessage() snapshot = message.retrieve_snapshot snapshot.snapshot_id = snapshot_id total_balance = 0 print("snapshot_id: %d" % snapshot_id) for branch in all_branches: soc = sockets[branch.name] soc.send(message.SerializeToString() + '\0') ret = soc.recv(1024) snapshot_message = bank_pb2.BranchMessage() try: snapshot_message.ParseFromString(ret) balance, channel_state = parse_snapshot(snapshot_message, branch.name) print("%s: %4d, %s" % (branch.name, balance, channel_state)) total_balance += balance except Exception as e: print("error %s" % e)
def initbranch(self): try: num_of_branches = sum(1 for line in open(self.FILENAME)) except: print "EXCEPTION ! Error opening input file" sys.exit(0) if num_of_branches < 2 : print "EXCEPTION ! Input file should contain at least 2 branches" sys.exit(0) try: balance = int ( self.TOTAL_BALANCE ) / int ( num_of_branches ) except: print "EXCEPTION ! Input file expty" sys.exit(0) with open(self.FILENAME, 'rU') as f: for line in f: branchname,ipaddress,portnumber = line.split(" ") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST, PORT = ipaddress, int(portnumber) init_branch_msg = bank_pb2.InitBranch() init_branch_msg.balance = int(balance) with open(self.FILENAME, 'rU') as f: for line in f: branchname1,ipaddress1,portnumber1 = line.split(" ") pb_branch = init_branch_msg.all_branches.add() pb_branch.name = branchname1 pb_branch.ip = ipaddress1 pb_branch.port = int(portnumber1) branchUpdateMessage = bank_pb2.InitBranch.Branch() branchUpdateMessage.name = branchname branchUpdateMessage.ip = ipaddress branchUpdateMessage.port = int(portnumber) pb_msg = bank_pb2.BranchMessage() pb_msg.init_branch.CopyFrom(init_branch_msg) encoded = pb_msg.SerializeToString() self.socket_obj.send_message_Protobuf(HOST , PORT, encoded) pb_message = bank_pb2.BranchMessage() pb_message.ParseFromString(encoded) self.list = pb_message.init_branch.all_branches list1 = [] for item in self.list: list1.append(item) self.list = list1
def handle_snapshots(): sid = 1 while True: # choose a branch at random from branch_list r_branch = _rch(branch_list) handle_init(r_branch) time.sleep(len(branch_list) * 10) r_snap_msg = bank_pb2.BranchMessage() r_snap_msg.retrieve_snapshot.snapshot_id = sid r_snap_msg = r_snap_msg.SerializeToString() print('\n\nSnapshot id : {}'.format(sid)) sid += 1 for _ in connections: size = encode_varint(len(r_snap_msg)) connections[_].sendall(size + r_snap_msg) data = b'' while True: try: data += connections[_].recv(1) size = decode_varint(data) break except IndexError: pass msg = connections[_].recv(size) t_msg = bank_pb2.BranchMessage() t_msg.ParseFromString(msg) #for i in range(len(branch_list)-len(t_msg.return_snapshot.local_snapshot.channel_state)): # t_msg.return_snapshot.local_snapshot.channel_state.append(0) print('\n{} : {},'.format( _, t_msg.return_snapshot.local_snapshot.balance), end=' ') chan_state = [] p_str = '' l = [ f[0].name for f in t_msg.return_snapshot.local_snapshot.ListFields() ] if 'channel_state' not in l: p_str += ' '.join('{}->{} : {},'.format(each, _, 0) for each in branch_list if each != _) else: for f in t_msg.return_snapshot.local_snapshot.ListFields(): if f[0].name == 'channel_state': for i in range(len(f[1])): chan_state.append(f[1][i]) for i in range(len(branch_list) - len(chan_state)): chan_state.append(0) for i in range(len(branch_list)): if branch_list[i] == _: chan_state[-1] = chan_state[i] else: p_str += ' {}->{} : {},'.format( branch_list[i], _, chan_state[i]) c_logger.debug(p_str[:-1])
def send_money_to_branches(total_balance, branches): balance_per_branch = int(total_balance) / len(branches) print "Sending " + str( balance_per_branch) + " per branch to these branches: " + str( [x[0] for x in branches]) # Generate and populate the init_branch message init_branch_msg = bank_pb2.InitBranch() init_branch_msg.balance = balance_per_branch for branch in branches: pb_branch = init_branch_msg.all_branches.add() pb_branch.name = branch[0] pb_branch.ip = branch[1] pb_branch.port = int(branch[2]) pb_msg = bank_pb2.BranchMessage() pb_msg.init_branch.CopyFrom(init_branch_msg) branch_sockets = [] # Establish connections to all branches and send them the init_branch message. # Also record the socket objects created which will be used later to send snapshot messages. for branch in branches: client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((branch[1], int(branch[2]))) client_socket.send(pb_msg.SerializeToString()) branch_sockets.append((client_socket, branch[0])) return branch_sockets
def initialize_bank(money, branches_file): with open(branches_file, 'r') as f: branches = [line.split() for line in f] branch_money = int(money / len(branches)) remainder = money - (branch_money * len(branches)) init = bank_pb2.InitBranch() init.balance = branch_money for branch_arr in branches: branch = init.all_branches.add() branch.name = branch_arr[0] branch.ip = branch_arr[1] branch.port = int(branch_arr[2]) message = bank_pb2.BranchMessage() message.init_branch.MergeFrom(init) for branch in message.init_branch.all_branches: print(branch.name) print(branch.ip) print(branch.port) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((branch.ip, branch.port)) sockets.append((sock, branch.name)) if remainder == 0: message.init_branch.balance = branch_money message_socket(sock, message) else: message.init_branch.balance = branch_money + remainder message_socket(sock, message) remainder = 0
def recv_marker(self, marker, connection): print '/nRecieved Marker :' snap_id = marker.snapshot_id sender = self.connections_branch_dict[connection] local_snap = self.snap_shot_list[snap_id] if snap_id not in self.marker_list: self.marker_list.append(snap_id) '''records its own local state (balance)''' local_snap.balance = self.balance '''records the state of the incoming channel from the sender to itself as empty''' channel_state = [self.channel_states[b] if self.all_branches[b] != sender else 0 for b in range(len(self.all_branches))] local_snap.channel_state = channel_state '''immediately starts recording on other incoming channels''' '''sends out Marker messages to all of its outgoing channels''' branch_msg = bank_pb2.BranchMessage() branch_msg.marker.snapshot_id = snap_id message = branch_msg.SerializeToString() self.send_messsage_all(message=message) else: '''records the state of the incoming channel as the sequence of money transfers that arrived between when it recorded its local state and when it received the Marker''' local_snap = self.snap_shot_list[snap_id] channel_state = [self.channel_states[b] for b in range(len(self.all_branches))] local_snap.channel_state = channel_state
def listen_for_message(self, client_socket, client_add): msg = client_socket.recv(1024) if msg: for m in msg.split('\0')[:-1]: branch_message = bank_pb2.BranchMessage() branch_message.ParseFromString(m) self.parse_message(client_socket, client_add, branch_message)
def init_each_server(self, branch_index, init_balance): branch = self.all_branches[branch_index] branch_msg = bank_pb2.BranchMessage() init_branch_temp = branch_msg.init_branch init_branch_temp.balance = init_balance # init_branch_temp.all_branches = self.all_branches for b in self.all_branches: temp_branch = init_branch_temp.all_branches.add() temp_branch.name = b.name temp_branch.ip = b.ip temp_branch.port = b.port message = branch_msg.SerializeToString() print self.branch_conn_dict print "initBranch message :", branch.name print message try: self.branch_conn_dict[branch_index].sendall(message) finally: # server.close() pass
def start_handling_messages(self): pb_msg = bank_pb2.BranchMessage() while True: incoming_message = self.client_socket.recv(MAX_REQUEST_SIZE) pb_msg.ParseFromString(incoming_message) if len(incoming_message) == 0: # Didn't read anything from socket continue # Call specific handlers depending on type of the incoming message if pb_msg.HasField("transfer"): self.handle_transfer_message(pb_msg) elif pb_msg.HasField("init_snapshot"): SnapshotHandler.handle_init_snapshot(pb_msg) elif pb_msg.HasField("marker"): SnapshotHandler.handle_marker(pb_msg, self.remote_branch_name) elif pb_msg.HasField("retrieve_snapshot"): reply = SnapshotHandler.handle_retrieve_snapshot(pb_msg) self.send_msg_to_remote(reply) if not reply: sys.exit(1) else: print "ERROR! Message type not identified. This is the message : " + str( pb_msg)
def handle_retrieve_snapshot(cls, incoming_message): snapshot_id = incoming_message.retrieve_snapshot.snapshot_id if snapshot_id not in cls.current_snapshots: # Asked to retrieve a snapshot which doesn't exist print "ERROR! Asked to retrieve a snapshot ID (" + str( snapshot_id) + ") which doesn't exist!" return None # Create the return_snapshot object and local_snapshot object pb_msg = bank_pb2.BranchMessage() return_snapshot_obj = bank_pb2.ReturnSnapshot() local_snapshot_obj = return_snapshot_obj.LocalSnapshot() local_snapshot_obj.snapshot_id = snapshot_id # Populate the local_snapshot object for state in cls.current_snapshots[snapshot_id]: if state != "local": local_snapshot_obj.channel_state.append( cls.current_snapshots[snapshot_id][state]) else: local_snapshot_obj.balance = cls.current_snapshots[ snapshot_id][state] return_snapshot_obj.local_snapshot.CopyFrom(local_snapshot_obj) pb_msg.return_snapshot.CopyFrom(return_snapshot_obj) return pb_msg
def handle_snapshot(self, message, initial=True): print('snapshot_id: {}'.format(message.snapshot_id)) if not initial: print('From: {}'.format(message.branch_name)) # Set marker marker = bank_pb2.Marker() marker.branch_name = self.name marker.snapshot_id = message.snapshot_id # Create local snapshot to send later stored_snapshot = bank_pb2.ReturnSnapshot() stored_snapshot.local_snapshot.snapshot_id = message.snapshot_id # Set balance of local snapshot and default value channel_states stored_snapshot.local_snapshot.balance = self.balance stored_snapshot.local_snapshot.channel_state[:] = [ 0 for _ in range(len(self.branches)) ] print('Initial channel_state') print(stored_snapshot.local_snapshot.channel_state) # Store local snapshot which means it has seen snapshot_id self.snapshots[message.snapshot_id] = (stored_snapshot, True) self.channel_states[message.snapshot_id] = [ 0 for _ in range(len(self.branches)) ] if not initial: incoming_channel_index = self.get_branch_index(message.branch_name) # Set incoming channel as empty for snapshot self.channel_states[ message.snapshot_id][incoming_channel_index] = None new_message = bank_pb2.BranchMessage() new_message.marker.MergeFrom(marker) for sock in self.sockets: sock[1].acquire() self.message_socket(sock[0], new_message) sock[1].release()
def contact_branches(self): branches = self._parse_file() init_balance = self.total_init_balance / len(branches) # print init_balance protobuf_branches = [] for br in branches: curr_branch = bank_pb2.InitBranch().Branch() curr_branch.name = br.name curr_branch.ip = br.ip curr_branch.port = int(br.port) protobuf_branches.append(curr_branch) initbranch = bank_pb2.InitBranch() initbranch.balance = init_balance initbranch.all_branches.extend(protobuf_branches) branchmsg = bank_pb2.BranchMessage() branchmsg.init_branch.CopyFrom(initbranch) for br in branches: s = socket.socket() s.connect((br.ip, int(br.port))) s.sendall(branchmsg.SerializeToString()) self.branch_connections.append(s) sleep(10)
def sleep_thread(): global balance global branches_all global branch_soc_list global port t = float(sys.argv[3]) while 1: print "Sleeping for", t / 1000, "seconds" sleep(t / 1000) print "Woke up" transfer_msg = bank_pb2.Transfer() withdraw = randint(10, 50) val = random.choice(branch_soc_list.keys()) if withdraw <= balance: transfer_msg.money = withdraw transfer_msg.src_branch = sys.argv[2] transfer_msg.dst_branch = str(val) send_message = bank_pb2.BranchMessage() send_message.transfer.CopyFrom(transfer_msg) lock = threading.Lock() lock.acquire() if not RECORD[int(val)]: print "Sending", withdraw, "to", val balance -= withdraw branch_soc_list[val].sendall(send_message.SerializeToString()) print "Remaining balance is:", balance else: print "Not sending to", val lock.release()
def Amount_Receive(self, clientSocket, clientAddress): while 1: msg = clientSocket.recv(10000) self.receive_amt_Lock.acquire() trans_msg = bank_pb2.BranchMessage() trans_msg.ParseFromString(msg) if trans_msg.HasField('transfer'): self.balance_Lock.acquire() self.balance += trans_msg.transfer.money self.balance_Lock.release() # Recording incoming channel states if self.record[trans_msg.transfer.src_branch] == True: #recv_channel=trans_msg.transfer.src_branch + '_to_' + trans_msg.transfer.dst_branch recv_channel = trans_msg.transfer.src_branch if recv_channel in self.temp_dict.keys(): self.temp_dict_lock.acquire() self.temp_dict[recv_channel].append( trans_msg.transfer.money) self.temp_dict_lock.release() else: self.temp_dict_lock.acquire() self.temp_dict[recv_channel] = [] self.temp_dict[recv_channel].append( trans_msg.transfer.money) self.temp_dict_lock.release() print "Received money from " + trans_msg.transfer.src_branch + " Balance = " + str( self.balance) self.receive_amt_Lock.release()
def sendReturnSnapshot(self): snapshot = bank_pb2.ReturnSnapshot() snapshot.local_snapshot.snapshot_id = self.snapshot_id #snapshot.local_snapshot.balance = self.snapshotBalance snapshot.local_snapshot.balance = self.snapshots[ self.snapshot_id].balance # First get senders in sorted order senders = [] for port in self.branches.keys(): sender = self.branches[port].name senders.append(sender) senders.sort() channel_states = [] for sender in senders: amount = self.snapshots[self.snapshot_id].getChannel(sender) channel_states.append(amount) #for branch in sorted(self.commChannel.keys()): # #snapshot.local_snapshot.channel_state.extend(self.commChannel[branch]) # channel_states.append(self.commChannel[branch]) snapshot.local_snapshot.channel_state.extend(channel_states) bm = bank_pb2.BranchMessage() bm.return_snapshot.CopyFrom(snapshot) print('ReturnSnapshot to send to Controller', bm) # Send to Controller self.sendMessageToController(bm)
def SendInitSnapshotMessage(self): # randomly select a branch to initate a snapshot RandomBranch = random.choice(self.list) NextIp = RandomBranch.ip NextPort = RandomBranch.port NextBranch = RandomBranch.name init_snapshot_msg = bank_pb2.InitSnapshot() init_snapshot_msg.snapshot_id = int(self.snapshot_num) pb_msg = bank_pb2.BranchMessage() pb_msg.init_snapshot.CopyFrom(init_snapshot_msg) encoded = pb_msg.SerializeToString() ip = NextIp port_num = NextPort message = encoded try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip, int(port_num))) x = pack('>I', len(message)) sock.sendall(x) sock.sendall(message) header = sock.recv(4) sock.close() except: print "EXCEPTION ! Socket exception in SendInitSnapshotMessage" sys.exit(0)
def MoneyTransfer(self): global TOTAL_BALANCE global branchName global branhList global moneyTransfer global timeLimit while True: logger.debug("Money Transfer.............") logger.debug("Money Transfer Status = "+str(moneyTransfer) +" Current Branch Balance = "+ str(TOTAL_BALANCE)) if moneyTransfer == True and TOTAL_BALANCE>50: randomBranch = random.choice(branhList) print randomBranch.ip print randomBranch.port MoneyTransferMsg = bank_pb2.Transfer() MoneyTransferMsg.money = (int) ((TOTAL_BALANCE* random.randint(1,5)) /100) MoneyTransferMsg.src_branch = branchName with self.critical_section_lock: if moneyTransfer == True : TOTAL_BALANCE = TOTAL_BALANCE - MoneyTransferMsg.money branchsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) branchsocket.connect((randomBranch.ip, randomBranch.port)) branchMessage = bank_pb2.BranchMessage() branchMessage.transfer.CopyFrom(MoneyTransferMsg) branchsocket.sendall(pickle.dumps(branchMessage)) branchsocket.close() print "Time limit +++++++ " + str(timeLimit) time.sleep(random.uniform(0, 5))
def sendTransactions(): global BRANCH_NAME global BRANCH_BALANCE global BRANCH_LIST global isUpdate while doTransfer: random_entry = random.choice(BRANCH_LIST) if BRANCH_BALANCE > 50: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((random_entry["ip"], random_entry["port"])) transfer = bank_pb2.Transfer() transfer.money = (BRANCH_BALANCE * random.randrange(1, 5)) / 100 msg = bank_pb2.BranchMessage() msg.transfer.CopyFrom(transfer) BRANCH_BALANCE = BRANCH_BALANCE - transfer.money s.sendall(pickle.dumps(msg)) s.close() if MARKER_MSG > 1 or isCapturing: isUpdate = True print "TRANSFERRING %s to %s...Remainging Balance: %s\n" % (str( transfer.money), str( random_entry["name"]), str(BRANCH_BALANCE)) time.sleep(random.randrange(1, 5))
def create_retrieve_snap(self): global init_counter branch_msg = bank_pb2.BranchMessage() ret = bank_pb2.RetrieveSnapshot() ret.snapshot_id = init_counter branch_msg.retrieve_snapshot.CopyFrom(ret) return branch_msg
def send_markers(self, snapshot_id): branch_msg = bank_pb2.BranchMessage() markr = bank_pb2.Marker() markr.snapshot_id = snapshot_id markr.branch_name = self.branch_name branch_msg.marker.CopyFrom(markr) for connections in self.connections: connections.sendall(branch_msg.SerializeToString())
def handle_init(r_branch): global snap_id branch_msg = bank_pb2.BranchMessage() branch_msg.init_snapshot.snapshot_id = snap_id snap_id += 1 branch_msg = branch_msg.SerializeToString() size = encode_varint(len(branch_msg)) connections[r_branch].sendall(size + branch_msg)
def initialize_snapshot(snapshot_id, sock): init = bank_pb2.InitSnapshot() init.snapshot_id = snapshot_id message = bank_pb2.BranchMessage() message.init_snapshot.MergeFrom(init) print(message.WhichOneof('branch_message')) print('Starting snapshot on: {}'.format(sock[1])) message_socket(sock[0], message)
def create_init_msg(self): global init_counter branch_msg = bank_pb2.BranchMessage() init = bank_pb2.InitSnapshot() init.snapshot_id = init_counter branch_msg.init_snapshot.CopyFrom(init) init_counter += 1 return branch_msg
def init_snapshot(self, msg): snapshot_id = msg.snapshot_id marker_msg = bank_pb2.BranchMessage() marker_msg.marker.snapshot_id = snapshot_id self.balance_lock.acquire() snap_obj = Snapshot(snapshot_id, self.balance) self.balance_lock.release() self.send_marker_msgs(marker_msg, snap_obj)
def initBranch(fname, total_balance): count = 0 BR = bank_pb2.BranchMessage() #store branch name, ip , port with open(fname) as f: for line in f: ip = line.split()[1] #port = line.split()[2] inport = int(line.split()[2].strip('\0')) init_branch = BR.init_branch branch = init_branch.all_branches.add() branch.name = line.split()[0] branch.ip = ip branch.port = inport count = count + 1 temp_list = [] temp_list.append(ip) temp_list.append(inport) branches[line.split()[0]] = temp_list branch_name.append(line.split()[0]) f.close() #initial balance of branches init_branch.balance = int(int(total_balance) / count) # Sending init branch message print "Sending init_branch message to all branches" with open(fname) as f: for line in f: ip = line.split()[1] port = line.split()[2] inport = int(port.strip('\0')) try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip, int(inport))) s.send(BR.SerializeToString()) print s.recv(100000) s.close() except: print "Not able to connect to " + line + " " + str( sys.exc_info()[0]) sys.exit(0) f.close()
def receive(self, connection): with Controller.recv_lock: msg = connection.recv(2048) branch_msg = bank_pb2.BranchMessage() branch_msg.ParseFromString(msg) if branch_msg.WhichOneof("branch_message") == "return_snapshot": self.recv_return_snapshot(branch_msg.return_snapshot, connection=connection) else: print "recieved : ", msg