Ejemplo n.º 1
0
	def heartBeat(self):
		for service in self.services.getServices():
			index = 0
			lbPort = service.getLbPort()
			for server in service.getServers():

				socket = SocketConnection()

				try:
					socket.connect(server.getIp(),server.getPort())
					print "STATUS OK"
					server.setStatus(True)
				except Exception,e:
					# cannot connect with server
					#print e
					#print "STATUS DOWN"
					server.setStatus(False)
				finally:
					socket.close()
Ejemplo n.º 2
0
        def eventBeatWorker(self,lbPort,eventPort,services,index):
            server = services.getServer(lbPort,index)
	    socket = SocketConnection()
	    try:
	    	#socket.connect(server.getIp(),int(eventPort),30)
	    	socket.connect(server.getIp(),int(eventPort),int(sdnlb_conf.iperf_tout)*3)
                if (sdnlb_conf.algo =="cpu"):
		        cmd = "iperf"
			args = []
                elif (sdnlb_conf.algo == "connections"):
		        cmd = "netstat"
			args = [server.getPort()]

		msg = JsonMessage.genCmdReqMessage(cmd,args)
		socket.send(msg)
	    	msg = socket.receive()
                #DEBUG
                print "HB msg recv:",msg
                #FINDEBUG
	    	
	    	if msg != '':
	    		(msgtype, data) = JsonMessage.parse_json(msg)
			
			if (msgtype == msgTypes['cmd_ans']):
				if (data['cmd'] == "iperf"):
					port = int(data['args'])
					time.sleep(4) # wait for iperf to start running	
					cmd = 'iperf3 -c %s -t %d -p %d -J'%(server.getIp(),int(sdnlb_conf.iperf_tout),int(port))

	                                p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
	                                output = p.stdout.read()
			                json_msg = JsonMessage.parse_iperf_json(output)
					if (json_msg['end']['cpu_utilization_percent']['remote_system'] != None):
						#cpu_load = json_msg['end']['cpu_utilization_percent']['remote_system']
						cpu_load = json_msg['end']['cpu_utilization_percent']['remote_total']
						#DEBUG
                                                print "CPU_LOAD:",cpu_load
						#FINDEBUG
						server.setCpu(float(cpu_load))

				elif (data['cmd'] == "netstat"):
					connections = int(data['args'])
					server.setConnections(int(connections))
					#DEBUG
                                        print "EB CONNS:",connections
					#FINDEBUG

                                    

            except Exception,e:
	    	# cannot connect with server
                #print "Exception"
	    	#print e
	    	#print "STATUS DOWN"
                server.setStatus(False)
Ejemplo n.º 3
0
    def unlock_car(self):
        """
        Perform functions for unlocking the car.
        """
        # GUI Loop.
        in_booking = True
        while in_booking:
            current_username = self.unlocked_car["username"]
            print("Welcome {}".format(current_username))
            print("Please select from the following options:\n \
            1. Return the Car.")
            # print("9. Update face recognition profile.")
            user_choice = input("Enter your choice: ")

            if user_choice == "1":
                # TODO how do we update the master if the connection fails?
                socket_connection = SocketConnection(
                    self.unlocked_car["car_id"])
                socket_connection.terminate_booking()
                in_booking = False
            elif user_choice == "9":
                # Confirm the user's intent after warnings.
                print(
                    "Warning: Continuing will remove your existing face profile for this vehicle!"
                )
                confirmation = input(
                    "Enter \"f\" to continue or any other choice to cancel: ")
                if confirmation != "f":
                    os.system("clear")
                    continue

                os.system("clear")
                print("Look directly at the camera for 15 seconds")

                # Update the user's face:
                # In future if the MasterPi has the resources, it may be better to
                # 1. Prompt for a password. If this password is valid, the
                # Master Pi will respond with a token which is then passed to the
                # face recognition creator for creation. For exanple:
                # print("To update your face recognition profile, please re-enter your password.")
                # password = getpass()

                # In this implementation, we simply call the FR software, updating
                # the faces in the user's folder and then updatating the pickle file.
                # This uses an agreed upon token - the hash of the username.
                hashing = hashlib.sha256(current_username.encode("utf-8"))
                user_token = hashing.hexdigest()
                log.info("Hashed username({}): {}".format(
                    current_username, user_token))
                faces_folder = "data_folder"
                face_pickle = "face_encodings.pickle"

                # Instantiate the FaceCapture object and attempt to capture
                # a face. If this is successful, re_encode the pickle file.
                face_capture = FaceCapture(user_token, faces_folder)
                capture_success = face_capture.capture_face()
                if capture_success:
                    print("Encoding Faces - please wait....")
                    face_encoder = FaceEncoder(faces_folder, face_pickle)
                    encoding_success = face_encoder.encode_faces()
                    if encoding_success:
                        print("Faces Encoded!")
                    else:
                        print("Encoding Error - this error has been logged.")
                        log.exception("Encoding error with current dataset.")
                else:
                    print("Unable to capture adequate face images.")

            time.sleep(3)
            os.system("clear")
        return
Ejemplo n.º 4
0
 def __init__(self, userselection: int, current_car: CarDetails):
     self.userselection = userselection
     self.current_car = current_car
     log.info("Current Car object in init: {}".format(self.current_car))
     self.socket_connection = SocketConnection(
         self.current_car.get_car_id())
Ejemplo n.º 5
0
class ValidateUser:
    """
    Validation entrypoint from the CLI. This can only be operated on when instantiated.
    This reduces unwarranted use of the validation function, and must be instantiated
    with the user's selection, and the class that contains the relevant data structurs.
    Without a valid selection, this will return False.
    """
    def __init__(self, userselection: int, current_car: CarDetails):
        self.userselection = userselection
        self.current_car = current_car
        log.info("Current Car object in init: {}".format(self.current_car))
        self.socket_connection = SocketConnection(
            self.current_car.get_car_id())

    def validateCredentials(self) -> bool:
        """
        This function is the entrypoint for any instantiation of this class.
        Solely for directing the user's choice to the appropriate function.
        Returns false if an invalid choice is made, otherwise returns
        true to indicate a return to the base state.
        """
        log.info("User Choice: {choice}".format(choice=self.userselection))
        if self.userselection == "1":
            self.validate_text()
            return True
        elif self.userselection == "2":
            self.validate_face()
            return True
        elif self.userselection == "9":
            self.validate_engineer()
            return True
        else:
            return False

    def validate_text(self):
        """
        Validates user's text credentials. Internally called. Returns after the number of attempts
        is exceeded or the user was true and the car has been returned.
        """

        attempts = 3
        #is_valid_user = False
        while attempts > 0:
            username = input(
                "\nPlease enter your log in details: \nUsername: "******"Validating credentials....")
            # TODO test whether it is necessary to clear the keyboard input....
            returned_dict = self.socket_connection.validate_text_credentials(
                username, password)

            log.info("Returned_dict: {}".format(returned_dict))
            # Check if the connection returned a result, if not inform.
            # TODO This could be moved to its own function so that both validation functions can call it.
            if returned_dict is None:
                print("Try again later.")
                time.sleep(3)
                return

            # Progressing this far means the result was a dictionary or False.
            # Unlock the car and break, so when the car is locked and
            # control is returned to this function, the program returns
            # to the main menu.
            if returned_dict is not False:
                # self.current_car.currenuser = username
                # Action unlock. From here all actions during a booking should take
                # place in and throughout this function call.
                # Return to the main menu. (cascades back through calling functions)

                # TODO Temporary - the unlock function called should be passed the
                # the username to unlock the car.
                #self.current_car.unlock_car(username)
                self.current_car.unlock_car(returned_dict)
                break

            # decrement attempts and inform the user.
            attempts = attempts - 1
            print("Credentials invalid for this car at this time!\n\
            Attempts remaining: {remains}".format(remains=attempts))

    def validate_face(self):
        """
        Attempts to validate a face detection. Instantiates and calls the 
        :mod:`facerecognition` which accepts one parameter, the location of the 
        encodings file (pickle) and returns the token if the face is in the database
        for validation with the server.
        """
        face_validator = FaceRecognition("face_encodings.pickle")
        user_token = face_validator.recognise_face()

        # The previous call returns None if no match was found. Otherwise,
        # the token is passed to the socket_connection call to validate
        # the booking - see socketconnection for return details, and above code in
        # credentials validation for example.
        if user_token is not None:
            print("Validating Booking.... {}".format(user_token))
            returned_dict = self.socket_connection.validate_face_credentials(
                user_token)
            log.info("returned_dict: {}".format(returned_dict))
            if returned_dict is None:
                print("Unable to connect to Server - try again later.")
                time.sleep(3)
                return
            if returned_dict is not False:
                # Action unlock. From here all actions during a booking should take
                # place in and throughout this function call.
                # Return to the main menu when done (cascades back through calling functions).
                self.current_car.unlock_car(returned_dict)
                return
            else:
                print("Booking not found.")
                time.sleep(3)
                return
        else:
            print("Face not recognised!\nPlease login with credentials.")
        time.sleep(2)
        return

    def validate_engineer(self):
        """
        This function is called when an engineer attempts to log in.
        It calls the appropriate bluetooth detection function in 
        the :mod:`bluetoothlistener` module and if an address is returned
        it then calls the socket connection and acts based on the return.
        """

        # Inform the user of the choice and action. Call bluetooth
        # detection function and act based on number of devices found.
        print("Validating engineer presence. \n \
        Please ensure your registered blueooth device is active....")
        btvalidation = bluetoothlistener.BluetoothListenerEngineer()
        detected_devices = btvalidation.catch_bluetooth()
        if len(detected_devices) > 0:
            # Devices were detected - determine if there is a valid
            # engineer booking at this car, acting appropriately
            # depending on the return.
            print("Validating device....")
            returned_dict = self.socket_connection.validate_engineer(
                detected_devices)
            log.info("returned_dict: {}".format(returned_dict))
            if returned_dict is None:
                print("Unable to establish server connection.")
                time.sleep(3)
                return
            if returned_dict is not False:
                self.current_car.engineer_access(returned_dict)
            else:
                print("No authorised devices detected. \n \
                Access denied!")
                time.sleep(3)
                return
        else:
            print("No devices found.")
            time.sleep(3)
            return