def cml_bench_sign_in(self): """ Establish active connection to CML-Bench :return: connection status (True or False) """ if not self.__app_session.key_file_path: self.__username = terminal.request_string_input("Username") self.__password = terminal.request_hidden_input("Password") else: credentials_info = KeyFileInformation( self.__app_session.key_file_path) if credentials_info.status_code != 0: terminal.show_error_message( credentials_info.status_description) sys.exit(credentials_info.status_code) else: self.__username = credentials_info.username self.__password = credentials_info.password login_response = self.__sender.send_login_request( self.__username, self.__password, False) self.__handler.set_response(login_response) connection_status = self.__handler.handle_response_to_login_request() if not connection_status: self.__username = '' self.__password = '' return connection_status
def get_submodels_list_from_database(self, cml_bench_path): xl = win32com.client.Dispatch("Excel.Application") wb = xl.Workbooks.Open(Filename=self.__database, ReadOnly=1) ws = wb.WorkSheets("Path") files = [] cols = [c.value for c in ws.Range("A2:T2")] i = 2 while i < 1000: j = 1 while j <= 20: val = ws.cells(i, j).value if val is not None: cols[j - 1] = val k = j + 1 while k <= 20: cols[k - 1] = None k += 1 break j += 1 if j > 20: terminal.show_error_message( "Database error. Path not found") wb.Close() return files path = '/'.join(col for col in cols if col is not None) if path == cml_bench_path: files = [ f.value for f in ws.Range("V" + str(i) + ":AO" + str(i)) if f.value is not None ] break i += 1 wb.Close() return files
def handle_raised_exception(exception): if isinstance(exception, Exception): terminal.show_error_message("Error occurred") tb = traceback.format_exception(etype=type(exception), value=exception, tb=None) terminal.show_trace_message("{}", "".join(tb))
def main(): config_path = abspath( join(abspath(dirname(getsourcefile(lambda: 0))), "config.cfg")) config_info = cfginfo.ConfigurationInformation(config_path) info = "" trace = "" code = 0 if config_info.status_code != 0: terminal.show_error_message(config_info.status_description) exit(config_info.status_code) else: try: appsession = AppSession(cfg=config_info) appsession.execute() except Exception as e: info = str(e) trace = traceback.format_exc() code = -100 else: info = "Correct termination" code = 0 finally: print(info) if trace: print(trace) exit(code)
def handle_response_to_add_loadcase_target_request(self): """ Handles response to add new loadcase target request :return: dictionary with keys: - `id` - `name` - `value` - `condition` - `dimension` containing information of created target, or None, if some error occurred """ response_json = self.__response.json() if response_json and isinstance(response_json, dict): target_id = response_json.get("id") target_name = response_json.get("name") target_value = response_json.get("value") target_condition = response_json.get("conditionId") target_dimension = response_json.get("dimension") if target_id: return { "id": target_id, "name": target_name, "value": target_value, "condition": target_condition, "dimension": target_dimension } terminal.show_error_message( "There were some errors during adding new target value!") return None
def handle_unexpected_exception(exception): if isinstance(exception, Exception): terminal.show_error_message("Unexpected exception occurred") tb = traceback.format_exception(etype=type(exception), value=exception, tb=exception.__traceback__) terminal.show_trace_message("{}", "".join(tb)) terminal.show_error_message("Terminating application")
def handle_response_to_task_status_response(self): response_json = self.__response.json() if response_json and isinstance(response_json, dict): task_status = response_json.get("status") if task_status: return task_status terminal.show_error_message("Failed to get task status.") return None
def handle_response_to_clone_simulation_request(self): response_json = self.__response.json() if response_json and isinstance(response_json, dict): simulation_id = response_json.get("id") if simulation_id: return simulation_id terminal.show_error_message("Failed to clone simulation.") return None
def handle_response_to_login_request(self): response_json = self.__response.json() if response_json and isinstance(response_json, dict): user = response_json.get("login") if user: terminal.show_info_message("Successfully connected as {}!".format(user)) return True terminal.show_error_message("Failed to connect!") return False
def handle_response_to_task_status_response(self): """ Handles response to task status request :return: current task status, or None, if some error occurred """ response_json = self.__response.json() if response_json and isinstance(response_json, dict): task_status = response_json.get("status") if task_status: return task_status terminal.show_error_message("Failed to get task status.") return None
def handle_response_to_clone_simulation_request(self): """ Handles response to clone simulation request :return: ID of cloned simulation, or None, if some error occurred """ response_json = self.__response.json() if response_json and isinstance(response_json, dict): simulation_id = response_json.get("id") if simulation_id: return simulation_id terminal.show_error_message("Failed to clone simulation.") return None
def handle_response_to_simulation_submodels_request(self): response_json = self.__response.json() list_of_submodels = [] if response_json and isinstance(response_json, list): for item in response_json: if item and isinstance(item, dict): item_id = item.get("id") if item_id: list_of_submodels.append(item_id) return list_of_submodels terminal.show_error_message( "There were some errors during reading simulation submodels!") return None
def handle_response_to_login_request(self): """ Handles response to login request :return: True if connection has been established, False otherwise """ response_json = self.__response.json() if response_json and isinstance(response_json, dict): user = response_json.get("login") if user: terminal.show_info_message( "Successfully connected as {}!".format(user)) return True terminal.show_error_message("Failed to connect!") return False
def handle_response_to_upload_submodel_request(self): response_json = self.__response.json() if response_json and isinstance(response_json, dict): status = response_json.get("status") if status == "success": submodels = response_json.get("set") if submodels and isinstance(submodels, list): if len(submodels) > 0: if isinstance(submodels[0], dict): submodel_id = submodels[0].get("id") return submodel_id terminal.show_error_message( "There were some errors during uploading new submodel!") return None
def handle_response_to_task_estimations_response(self): """ Handles response to task estimations :return: tuple of end waiting and end solving times, or None, if some error occurred """ from datetime import datetime response_json = self.__response.json() if response_json and isinstance(response_json, dict): task_end_waiting = response_json.get("expectedWaitingEndTime") task_end_solving = response_json.get("expectedSolvingEndTime") if task_end_waiting and task_end_solving: return (str(datetime.fromtimestamp(task_end_waiting // 1000)), str(datetime.fromtimestamp(task_end_solving // 1000))) terminal.show_error_message("Failed to get task estimations.") return None, None
def handle_response_to_stype_submodels_requests(self): response_json = self.__response.json() if response_json and isinstance(response_json, dict): list_of_submodels = [] content = response_json.get("content") if content and isinstance(content, list): for item in content: if item and isinstance(item, dict): submodel_id = item.get("id") if submodel_id: list_of_submodels.append(submodel_id) return list_of_submodels terminal.show_error_message( "There were some errors during reading s|type submodels!") return None
def handle_response_to_upload_submodel_request(self): """ Handles response to upload submodel request :return: dict with keys `to_insert` and `to_delete`, or None, of some error occurred """ response_json = self.__response.json() if response_json and isinstance(response_json, dict): result = {"to_insert": [], "to_delete": []} status = response_json.get("status") # if status is `success` get ids of uploaded submodels from set if status == "success": submodels = response_json.get("set") if submodels and isinstance(submodels, list): if len(submodels) > 0: if isinstance(submodels[0], dict): submodel_id = submodels[0].get("id") result["to_insert"].append(submodel_id) return result # if status is `warning` get ids of original submodels from duplicates # assuming that we uploading a single file every time if status == "warning": duplicates = response_json.get("duplicates") if duplicates and isinstance(duplicates, list): terminal.show_warning_message( "There are duplicate submodels on server!") if len(duplicates) > 0: if isinstance(duplicates[0], dict): created_object = duplicates[0].get("createdObject") if created_object and isinstance( created_object, dict): created_object_id = created_object.get("id") result["to_delete"].append(created_object_id) duplicate_objects = duplicates[0].get( "duplicateObjects") if duplicate_objects and isinstance( duplicate_objects, list): if len(duplicate_objects) > 0: original_object = duplicate_objects[0] if isinstance(original_object, dict): original_object_id = original_object.get( "id") result["to_insert"].append( original_object_id) return result terminal.show_error_message( "There were some errors during uploading new submodel!") return None
def handle_response_to_simulation_values_request(self): """ Handles response to simulation key results :return: list of dictionaries with keys `id`, `name`, `value`, `dimension`, `description`, `parent` representing simulation key results, or None, if some error occurred """ def remove_prefix(string, prefix): if string.startswith(prefix): return string[len(prefix):] return string response_json = self.__response.json() if response_json and isinstance(response_json, dict): list_of_values = [] content = response_json.get("content") if content: for item in content: if item and isinstance(item, dict): kr_id = item.get("id") kr_name = item.get("name") kr_dimension = None kr_value = None kr_description = item.get("description") kr_repr = item.get("overview").get("content") kr_parent = item.get("simulationId") kr_type = item.get("type") if kr_id and kr_type == "value": details_response = self.__app_session.sender.send_simulation_value_request( kr_parent, kr_id) if details_response and details_response.status_code == 200: details_response_json = details_response.json() kr_value = details_response_json.get(kr_name) kr_dimension = remove_prefix( str(kr_repr), str(kr_value)) list_of_values.append({ "id": kr_id, "name": kr_name, "value": kr_value, "dimension": kr_dimension, "description": kr_description, "parent": kr_parent }) return list_of_values terminal.show_error_message( "There were some errors during reading simulation key results") return None
def handle_response_to_loadcase_simulations_request(self): response_json = self.__response.json() if response_json and isinstance(response_json, dict): list_of_simulations = [] content = response_json.get("content") if content: for item in content: if item and isinstance(item, dict): simulation_id = item.get("id") if simulation_id: list_of_simulations.append(simulation_id) return list_of_simulations terminal.show_warning_message("No simulations read from loadcase!") return [] terminal.show_error_message( "There were some errors during reading loadcase simulations!") return None
def clone_simulation(self): terminal.show_info_message( "Trying to clone simulation with ID {}".format(self.search_id)) reference_simulation = self.search_for_simulation() if reference_simulation: cloned_simulation_id = reference_simulation.clone() terminal.show_info_message( "Cloned simulation ID: {}".format(cloned_simulation_id)) return terminal.show_error_message("Failed to clone simulation")
def handle_response_to_task_defaults_request(self): """ Handles response to default task parameters request :return: dictionary with request json parameters to run new task, or None, if some error occurred """ response = self.__response response_json_list = response.json() if isinstance(response_json_list, list) and response_json_list: defaults_json = response_json_list[0] if defaults_json and isinstance(defaults_json, dict): return defaults_json if response.status_code == 200 and not response_json_list: terminal.show_error_message( "Simulation defaults for task were not found!") return None terminal.show_error_message( "There were some errors during reading task defaults of this simulation!" ) return None
def handle_response_to_run_request(self): """ Handles response to run request :return: task ID if new task was created, or None otherwise """ response_json = self.__response.json() if response_json and isinstance(response_json, dict) and ("id" in response_json): task_identifier = response_json.get("id") return task_identifier if response_json and isinstance(response_json, dict) and ("message" in response_json): message = response_json.get("message") terminal.show_error_message( "Couldn't send simulation to run: \"{}!\"".format(message)) return None terminal.show_error_message( "There were some errors during sending simulation to run!") return None
def set_description(self, description): response = self._sender.send_entity_base_info_request( self.identifier, self.entity_type.value) Timeout.hold_your_horses() self._handler.set_response(response) payload = self._handler.get_full_server_base_response() if isinstance(payload, dict) and "description" in payload.keys(): payload["description"] = str(description) response = self._sender.send_modify_simulation_request( self.identifier, payload) Timeout.hold_your_horses() self._handler.set_response(response) result = self._handler.handle_response_to_update_simulation_request( description=description) return result else: terminal.show_error_message( "No description found in server response") return None
def handle_response_to_simulation_tasks_request(self): """ Handles response to simulation tasks request :return: list containing IDs of simulation tasks, or None, if some error occurred """ response_json = self.__response.json() if response_json and isinstance(response_json, dict): list_of_tasks = [] content = response_json.get("content") if content: for item in content: if item and isinstance(item, dict): task_id = item.get("id") if task_id: list_of_tasks.append(task_id) return list_of_tasks terminal.show_warning_message("No tasks read from simulation!") return [] terminal.show_error_message( "There were some errors during reading simulation tasks!") return None
def handle_response_to_delete_submodel_from_server_request(self): """ Handles response to delete submodel from server request :return: deleted submodel ID, if successfully deleted, or None otherwise """ response = self.__response if response.status_code == 200: response_json = self.__response.json() deleted_submodel_identifier = response_json.get("id") if deleted_submodel_identifier: return deleted_submodel_identifier if response.status_code == 409: response_json = self.__response.json() if response_json and isinstance(response_json, dict): message = response_json.get("message") terminal.show_error_message( "There were conflicts during deleting submodel from server: \"{}\"", message) return None if response.status_code == 403: response_json = self.__response.json() if response_json and isinstance(response_json, dict): message = response_json.get("message") terminal.show_error_message( "There were conflicts during deleting submodel from server: \"{}\"", message) return None # print(response) terminal.show_error_message( "There were some errors during deleting submodel from server!") return None
def main(): root_path = os.path.abspath( os.path.dirname(inspect.getsourcefile(lambda: 0))) print("Running script from: ", root_path) config_path = os.path.abspath(os.path.join(root_path, "cfg", "config.cfg")) config_info = ConfigurationInformation(config_path) info = "" trace = "" code = 0 credentials_file = None arguments = argparser.get_arguments() if arguments: key = arguments.k if key: credentials_file = os.path.abspath( os.path.join(root_path, "cfg", "credentials")) if config_info.status_code != 0: terminal.show_error_message(config_info.status_description) sys.exit(config_info.status_code) else: try: app_session = AppSession(cfg=config_info, credentials=credentials_file) app_session.execute() except Exception as e: info = str(e) trace = traceback.format_exc() code = -100 else: info = "Finished." code = 0 finally: print(info) if trace: print(trace) sys.exit(code)
def _collect_values(self): """ Collect all available key results from all current simulations Vertex status must be `Finished` :return: dictionary with input JSON-like internal structure """ output_data = { "Root": { "Behaviour": JSONTypes.VALUES.value, "LCs": [] } } vertices = list(self.graph.vertices.values()) assert all(isinstance(v, Vertex) for v in vertices) for v in vertices: if v.status != "Finished": terminal.show_error_message( f"Vertex {v.identifier} status is not \"Finished\"," + f"could not collect key results") continue values = v.current_simulation.get_values() current_values = [{ "name": val.name, "value": val.value, "dimension": val.dimension, "description": val.description } for val in values] output_data["Root"]["LCs"].append({ JSONProps.VERTEX_ID.value: v.identifier, JSONProps.LOADCASE_ID.value: v.base_simulation.get_loadcase().identifier, JSONProps.VALUES.value: current_values }) return output_data
def _change_targets(self): """ Processing input JSON with behaviour `Update targets` Send requests to add new targets :return: """ if self.json_type != JSONTypes.UPDATE_TARGETS.value: raise ValueError( "Method `change_targets()` can not be called for JSON of type `{}`" .format(self.json_type)) # Walk over each vertices # Vertex contains information about base simulation # Obtain Loadcase ID from base simulation # Add new targets to this loadcase vertices = list(self.graph.vertices.values()) assert all(isinstance(v, Vertex) for v in vertices) for v in vertices: base_simulation = v.base_simulation vertex_loadcase = v.loadcase parent_loadcase = base_simulation.get_loadcase() if vertex_loadcase.identifier != parent_loadcase.identifier: terminal.show_error_message( "Mismatch loadcase from `loadcase_id` " "and parent loadcase from `base_simulation_id`") lc = vertex_loadcase if vertex_loadcase is not None else parent_loadcase targets = v.targets for t in targets: ans = lc.add_target(t.get("name"), t.get("value"), t.get("condition"), t.get("dimension"), t.get("tolerance"), t.get("description")) if ans is not None: terminal.show_info_message( "Successfully added target {} to loadcase {}", ans.identifier, lc.identifier) else: terminal.show_error_message( "Failed to add target to loadcase {}", lc.identifier)
def handle_response_to_simulation_submodels_request(self): """ Handles response to simulation submodels request :return: list containing IDs of simulation submodels, or None, if some error occurred """ response_json = self.__response.json() list_of_submodels = [] if response_json and isinstance(response_json, list): for item in response_json: if item and isinstance(item, dict): item_id = item.get("id") if item_id: list_of_submodels.append(item_id) return list_of_submodels # for the case of empty response response_status = self.__response.status_code if response_status == 200: terminal.show_warning_message("Simulation has no submodels!") return list_of_submodels terminal.show_error_message( "There were some errors during reading simulation submodels!") return None
def handle_response_to_loadcase_targets_request(self): """ Handles response to loadcase targets request :return: list of dictionaries with keys: - `id` - `name` - `value` - `condition` - `dimension` containing information of loadcase targets, or None, if some error occurred """ response_json = self.__response.json() if response_json and isinstance(response_json, dict): targets_data = [] content = response_json.get("content") if content: for item in content: if item and isinstance(item, dict): target_id = item.get("id") target_name = item.get("name") target_value = item.get("value") target_condition = item.get("conditionId") target_dimension = item.get("dimension") if target_id: targets_data.append({ "id": target_id, "name": target_name, "value": target_value, "condition": target_condition, "dimension": target_dimension }) return targets_data terminal.show_warning_message("No targets read from loadcase!") return [] terminal.show_error_message( "There were some errors during reading loadcase targets!") return None