def Bypass(): while True: user_info_object = {'project': 'zeuz', 'team': 'zeuz'} oLocalInfo = CommonUtil.MachineInfo() testerid = (oLocalInfo.getLocalUser()).lower() print("[Bypass] Zeuz Node is online: %s" % testerid) RunProcess(testerid, user_info_object)
def command_line_args() -> Path: """ This function handles command line scripts with given arguments. Returns: `log_dir` - the custom log directory if specified, otherwise `None`. Example 1: 1. python node_cli.py 2. node_cli.py These 2 scripts will skip all kind of actions in this function because they dont have any arguments and will execute Login(CLI=true) from __main__ Example 2: 1. python node_cli.py --logout 2. node_cli.py --logout 3. node_cli.py -l These 3 scripts will will execute logout from server and then will execute Login(CLI=true) from __main__ then you have to provide server, username, password one by one in the terminal to login Example 3: 1. python node_cli.py --username USER_NAME --password PASS_XYZ --server https://zeuz.zeuz.ai 2. node_cli.py --logout --username USER_NAME --password PASS_XYZ --server https://zeuz.zeuz.ai 3. node_cli.py -u USER_NAME -p PASS_XYZ -s https://zeuz.zeuz.ai 4. python node_cli.py -k YOUR_API_KEY --server https://zeuz.zeuz.ai These 3 scripts will will execute logout from server and then will execute Login(CLI=true) from __main__ but you don't need to provide server, username, password again. It will execute the login process automatically for you Example 3: 1. python node_cli.py --help 2. node_cli.py --help 3. node_cli.py -h These 3 scripts will show the documentation for every arguments and will execute sys.exit() Example 4: 1. python node_cli.py --ussssername USER_NAME --password PASS_XYZ --server https://zeuz.zeuz.ai 2. node_cli.py --u USER_NAME -p PASS_XYZ -s 3. node_cli.py --logout https://zeuz.zeuz.ai Above are some invalid arguments which will show some log/documentation and will execute sys.exit() """ # try: parser_object = argparse.ArgumentParser("node_cli parser") parser_object.add_argument("-u", "--username", action="store", help="Enter your username", metavar="") parser_object.add_argument("-p", "--password", action="store", help="Enter your password", metavar="") parser_object.add_argument("-s", "--server", action="store", help="Enter server address", metavar="") parser_object.add_argument("-k", "--api_key", action="store", help="Enter api key", metavar="") parser_object.add_argument("-n", "--node_id", action="store", help="Enter custom node_id", metavar="") parser_object.add_argument( "-m", "--max_run_history", action="store", help="How many latest histories do you want to keep", metavar="") parser_object.add_argument("-l", "--logout", action="store_true", help="Logout from the server") parser_object.add_argument("-a", "--auto_update", action="store_true", help="Updates your Zeuz Node") parser_object.add_argument("-r", "--local_run", action="store_true", help="Performs a local run") parser_object.add_argument( "-o", "--once", action="store_true", help= "If specified, this flag tells node to run only one session (test set/deployment) and then quit immediately" ) parser_object.add_argument( "-d", "--log_dir", action="store", help="Specify a custom directory for storing Run IDs and logs.", metavar="") all_arguments = parser_object.parse_args() username = all_arguments.username password = all_arguments.password server = all_arguments.server api = all_arguments.api_key node_id = all_arguments.node_id max_run_history = all_arguments.max_run_history logout = all_arguments.logout auto_update = all_arguments.auto_update # Check if custom log directory exists, if not, we'll try to create it. If # we can't create the custom log directory, we should error out. log_dir = None try: if all_arguments.log_dir: log_dir = Path(all_arguments.log_dir.strip()) log_dir.mkdir(parents=True, exist_ok=True) # Try creating a temporary file to see if we have enough permissions # to write in the specified log directory. touch_file = log_dir / "touch" touch_file.touch() touch_file.unlink() except PermissionError: raise Exception( f"ERR: Zeuz Node does not have enough permissions to write to the specified log directory: {log_dir}" ) except: raise Exception( f"ERR: Invalid custom log directory, or failed to create directory: {log_dir}" ) global local_run local_run = all_arguments.local_run global RUN_ONCE RUN_ONCE = all_arguments.once if server and server[-1] == "/": server = server[:-1] if auto_update: check_for_updates() if username or password or server or logout or api: if api and server: ConfigModule.remove_config_value(AUTHENTICATION_TAG, "api-key") ConfigModule.add_config_value(AUTHENTICATION_TAG, "api-key", api) ConfigModule.remove_config_value(AUTHENTICATION_TAG, "server_address") ConfigModule.add_config_value(AUTHENTICATION_TAG, "server_address", server) elif username and password and server: ConfigModule.remove_config_value(AUTHENTICATION_TAG, "server_address") ConfigModule.add_config_value(AUTHENTICATION_TAG, "username", username) ConfigModule.add_config_value( AUTHENTICATION_TAG, "password", password_hash(False, "zeuz", password)) ConfigModule.add_config_value(AUTHENTICATION_TAG, "server_address", server) elif logout: ConfigModule.remove_config_value(AUTHENTICATION_TAG, "server_address") zeuz_authentication_prompts_for_cli() else: CommonUtil.ExecLog( "AUTHENTICATION FAILED", "Enter the command line arguments in correct format. Type -h for help.", 3, ) sys.exit() # exit and let the user try again from command line if node_id: CommonUtil.MachineInfo().setLocalUser(node_id) if max_run_history: pass """argparse module automatically shows exceptions of corresponding wrong arguments and executes sys.exit(). So we don't need to use try except""" # except: # CommonUtil.ExecLog("\ncommand_line_args : node_cli.py","Did not parse anything from given arguments",4) # sys.exit() return log_dir
def update_machine(dependency, default_team_and_project_dict): try: # Get Local Info object oLocalInfo = CommonUtil.MachineInfo() local_ip = oLocalInfo.getLocalIP() testerid = (oLocalInfo.getLocalUser()).lower() project = default_team_and_project_dict["project_name"] team = default_team_and_project_dict["team_name"] if not dependency: dependency = "" _d = {} for x in dependency: t = [] for i in x[1]: _t = ["name", "bit", "version"] __t = {} for index, _i in enumerate(i): __t.update({_t[index]: _i}) if __t: t.append(__t) _d.update({x[0]: t}) dependency = _d available_to_all_project = ConfigModule.get_config_value( "Advanced Options", "available_to_all_project") allProject = "no" if str(available_to_all_project).lower() == "true": allProject = "yes" update_object = { "machine_name": testerid, "local_ip": local_ip, "dependency": dependency, "project": project, "team": team, "device": device_dict, "allProject": allProject, } r = RequestFormatter.Get("update_automation_machine_api", update_object) if r["registered"]: CommonUtil.ExecLog( "", "Zeuz Node is online: %s" % (r["name"]), 4, False, ) else: if r["license"]: CommonUtil.ExecLog("", "Machine is not registered as online", 4, False) else: if "message" in r: CommonUtil.ExecLog("", r["message"], 4, False) CommonUtil.ExecLog("", "Machine is not registered as online", 4, False) else: CommonUtil.ExecLog("", "Machine is not registered as online", 4, False) return r except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] Error_Detail = ((str(exc_type).replace("type ", "Error Type: ")) + ";" + "Error Message: " + str(exc_obj) + ";" + "File Name: " + fname + ";" + "Line: " + str(exc_tb.tb_lineno)) CommonUtil.ExecLog("", Error_Detail, 4, False)
def RunProcess(sTesterid, user_info_object, run_once=False, log_dir=None): etime = time.time() + (30 * 60) # 30 minutes executor = CommonUtil.GetExecutor() while True: try: if exit_script: return False if time.time() > etime: print("30 minutes over, logging in again") return True # Timeout reached, re-login. We do this because after about 3-4 hours this function will hang, and thus not be available for deployment executor.submit(RequestFormatter.Get, "update_machine_with_time_api", {"machine_name": sTesterid}) # r = RequestFormatter.Get("is_run_submitted_api", {"machine_name": sTesterid}) r = RequestFormatter.Get( f"is_submitted_api?machine_name={sTesterid}") # r = requests.get(RequestFormatter.form_uri("is_submitted_api"), {"machine_name": sTesterid}, verify=False).json() Userid = (CommonUtil.MachineInfo().getLocalUser()).lower() if r and "found" in r and r["found"]: size = round(int(r["file_size"]) / 1024, 2) if size > 1024: size = str(round(size / 1024, 2)) + " MB" else: size = str(size) + " KB" save_path = temp_ini_file.parent / "attachments" CommonUtil.ExecLog( "", "Downloading dataset and attachments of %s into:\n%s" % (size, str(save_path / "input.zip")), 4) FL.CreateFolder(save_path) headers = RequestFormatter.add_api_key_to_headers({}) response = requests.get( RequestFormatter.form_uri("getting_json_data_api"), {"machine_name": Userid}, stream=True, verify=False, **headers) chunk_size = 4096 progress_bar = tqdm(total=r["file_size"], unit='B', mininterval=0, unit_scale=True, unit_divisor=1024, leave=False) with open(save_path / "input.zip", 'wb') as file: for data in response.iter_content(chunk_size): progress_bar.update(len(data)) file.write(data) progress_bar.refresh() progress_bar.close() z = zipfile.ZipFile(save_path / "input.zip") z.extractall(save_path) z.close() os.unlink(save_path / "input.zip") PreProcess(log_dir=log_dir) # Telling the node_manager that a run_id is deployed CommonUtil.node_manager_json({ "state": "in_progress", "report": { "zip": None, "directory": None, } }) try: MainDriverApi.main(device_dict, user_info_object) except: pass if run_once or exit_script: return False CommonUtil.ExecLog("", "Successfully updated db with parameter", 4, False) break else: time.sleep(3) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] Error_Detail = ((str(exc_type).replace("type ", "Error Type: ")) + ";" + "Error Message: " + str(exc_obj) + ";" + "File Name: " + fname + ";" + "Line: " + str(exc_tb.tb_lineno)) CommonUtil.ExecLog("", Error_Detail, 4, False) break # Exit back to login() - In some circumstances, this while loop will get into a state when certain errors occur, where nothing runs, but loops forever. This stops that from happening return True