def respond_start(message, sub_node, log_level, line_number_list=None): _primitives = primitives.Primitives(sub_node, log_level) arguments = _primitives.parse_cmd(message) print(arguments) if message.startswith("find"): line_number = arguments[0] token = arguments[1] print(line_number) if line_number in line_number_list: print("We found it") display_token(token) """Called by the client's listener_thread when it received a [name]: flag""" # find shelf for item num return line_number if message.startswith("reset"): line_number = arguments[0] if line_number in line_number_list: clear_display()
import os import sys import random # Allow us to import the client this_dir = os.path.dirname(os.path.realpath(__file__)) os.chdir(this_dir) sys.path.insert(0, (os.path.abspath('../../client'))) sys.path.insert(0, (os.path.abspath('../../server'))) import primitives import client _client = client.Client() _primitives = primitives.Primitives('Client', 'Debug') def initiate(net_tuple, arguments): """ Called from the network injector when it receives a $vote:(reason) input""" os.chdir(this_dir) import inject injector = inject.NetworkInjector() reason = arguments[0] # Start an election injector.broadcast("vote:" + reason, net_tuple) def respond_start(reason, nodeState): """Called by the client's listener_thread when it received a vote: flag"""
def config_net_size(arguments): try: if int(arguments[2]): with open('client_configuration.json', 'r') as client_configuration: client_config = json.load(client_configuration) client_config['net_size'] = int(arguments[2]) client_configuration.close() with open('client_configuration.json', 'w') as client_configuration: client_configuration.seek(0) json.dump(client_config, client_configuration) print(client_config['port']) client_configuration.close() except (ValueError, TypeError): print("That is not a valid port") _primitives = primitives.Primitives(sub_node, log_level) print(arguments, "there are the arguments") if arguments[0] == "network_size": try: new_network_size = int(arguments[1]) network_size = new_network_size _primitives.log("Successfully set network_size to: " + str(network_size), in_log_level="Info") except TypeError: _primitives.log("config: target value not int; ignoring...", in_log_level="Warning") elif arguments[0] == "network_architecture": # Changes from any architecture --> mesh must be done while network size <= 2 # any architecture --> fully-connected should always work new_network_architecture = arguments[1] if type(new_network_architecture) == str: network_architecture = new_network_architecture _primitives.log("Successfully set network_architecture to: " + network_architecture, in_log_level="Info") elif arguments[0] == "permanent": if arguments[1] == "port": change_port(arguments) elif arguments[1] == "network_architecture": pass elif arguments[1] == "remote_addresses": pass elif arguments[1] == "command_execution": pass elif arguments[1] == "default_log_level": pass elif arguments[1] == "modules": pass elif arguments[1] == "network_size" or arguments[1] == "net_size": config_net_size(arguments) pass else: print("Error \"" + arguments[1] + "\" isn't correct syntax")
import socket import struct import datetime import sys import os import secrets from hashlib import sha3_224 sys.path.insert(0, (os.path.abspath('../misc'))) sys.path.insert(0, (os.path.abspath('../inter/modules'))) import primitives Primitives = primitives.Primitives("Injector", "Debug") print("Connecting to localhost...") # Connect to localhost _socket = socket.socket() _socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) def prepare(message): """ Assign unique hashes to messages ready for transport. Returns (new hashed message) -> str """ # Sign the message timestamp = str(datetime.datetime.utcnow()) hash_input = timestamp + message sig = sha3_224(hash_input.encode()).hexdigest()[:16] out = sig + ":" + message
import csv import sys import os import urllib.request import urllib.error sys.path.insert(0, (os.path.abspath('../misc'))) import primitives import os _primitives = primitives.Primitives("Client", "Debug") def download_racks_csv(url): response = urllib.request.urlopen(url) data = response.read() # a `bytes` object text = data.decode( 'utf-8') # a `str`; this step can't be used if data is binary racks_file = open("Racks.csv", "w") racks_file.write(text) def find_my_parts(local_ip, directory_server, path_to_client=None): """Given a nodes static IP, find all part numbers assigned to it in the master spreadsheet Returns list [(part number, part name, line #), ..., (part number n, part name n, line # n)]""" if path_to_client: try: os.chdir(path_to_client) except FileNotFoundError: print("Directory does't exist: " + str(path_to_client)) return
def initialize(self, port=3704, listening=True, method="socket", network_injection=False, network_architecture="complete", default_log_level='Warning', modules=None): if method == "socket": global localhost global log_level global sub_node global Primitives log_level = default_log_level Primitives = primitives.Primitives(sub_node, log_level) for item in modules: import_str = "import " + item loaded_modules = self.read_nodestate(5) loaded_modules.append(item) self.write_nodestate(nodeState, 5, loaded_modules) exec(import_str) # Set parameters and global variables from their default values address_string = Primitives.get_local_ip()+":"+str(port) # e.x 10.1.10.3:3705 self.write_nodestate(nodeState, 3, network_injection) Primitives.log("Initializing... ", in_log_level="Info") Primitives.log(str("Server -> Binding server on: " + address_string + "..."), in_log_level="Info") # First, try to bind the server to (this address) port (port). If that doesn't work, exit cleanly. try: localhost.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) localhost.bind(('', port)) Primitives.log(str("Successfully bound server on port: " + str(port)), in_log_level="Info") except OSError: Primitives.log(str("Failed to bind server on " + address_string + "; Please try again later."), in_log_level="Info") self.stop() if listening: Primitives.log("Server -> Now Listening for incoming connections...", in_log_level="Info") # Listen for incoming connections. while listening: try: localhost.listen(5) client, address_tuple = localhost.accept() terminated = self.read_nodestate(2) if not terminated: address = address_tuple[0] self.append(client, address) connection = (client, address) # Our localhost connected, do localhost stuff; if address == Primitives.get_local_ip() or address == "127.0.0.1": Primitives.log("Localhost has connected.", in_log_level="Info") self.send(connection, str(no_prop+':'+"echo"), signing=False) self.listen(connection) Primitives.log("Listening on localhost...", in_log_level="Info") # Make the client connect back to localhost if network_architecture=mesh localhost_socket = self.lookup_socket("127.0.0.1") localhost_connection = (localhost_socket, "127.0.0.1") self.send(localhost_connection, no_prop + ":ConnectTo:" + address, signing=False) # A remote client connected, handle them and send an echo, because why not? else: Primitives.log(str(address + " has connected."), in_log_level="Info") Primitives.log(str("Listening on: "+address), in_log_level="Info") self.listen(connection) if network_architecture == "complete": self.send(connection, no_prop+":echo", signing=False) # WIP if network_architecture == "complete": # In a 'complete' network, every node is connected to every other node for redundancy. # Hence, when a new node connects, we broadcast it's address to the entire network so # every other node can try to connect to it (i.e 'complete' the network). self.broadcast(no_prop + ':ConnectTo:' + address) elif network_architecture == "mesh": # In mesh configuration, tell localhost client to connect back to the server # of any remote client which connects to localhost server. localhost_socket = self.lookup_socket("127.0.0.1") localhost_connection = (localhost_socket, "127.0.0.1") self.send(localhost_connection, no_prop + ":ConnectTo:" + address, signing=False) elif terminated: sys.exit(0) except ConnectionResetError: Primitives.log("Server -> localhost has disconnected", in_log_level="Warning") # OSError will occur on Windows Systems we try to terminate. Handle that. except OSError: sys.exit(0)
nodestate_lock = threading.Lock() send_lock = threading.Lock() receive_lock = threading.Lock() this_dir = os.path.dirname(os.path.abspath(__file__)) try: # This works when manually executing init_server.py from the current directory os.chdir(this_dir) except FileNotFoundError: # This works when launching with the src/misc/init.py script os.chdir("../../server") # This will be reset with input values by init() Primitives = primitives.Primitives(sub_node, log_level) original_path = os.path.dirname(os.path.realpath(__file__)) class Server: @staticmethod def lock(lock, name=None): # if name and type(name) == str: # print("locking " + name) lock.acquire() @staticmethod def release(lock, name=None):