Exemplo n.º 1
0
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
Exemplo n.º 2
0
def Login(cli=False, run_once=False, log_dir=None):
    username = ConfigModule.get_config_value(AUTHENTICATION_TAG, USERNAME_TAG)
    password = ConfigModule.get_config_value(AUTHENTICATION_TAG, PASSWORD_TAG)
    server_name = ConfigModule.get_config_value(AUTHENTICATION_TAG,
                                                "server_address")
    api = ConfigModule.get_config_value(AUTHENTICATION_TAG, "api-key")
    api_flag = True
    if not api or not server_name:
        zeuz_authentication_prompts_for_cli()
        for i in range(
                30):  # it takes time to save in the file. so lets wait 15 sec
            time.sleep(0.5)
            api = ConfigModule.get_config_value(AUTHENTICATION_TAG, "api-key")
            server_name = ConfigModule.get_config_value(
                AUTHENTICATION_TAG, "server_address")
            if api and server_name:
                break
    while api and server_name:
        url = '/api/auth/token/verify?api_key=%s' % (api)
        r = RequestFormatter.Get(url)
        if r:
            try:
                token = r['token']
                res = RequestFormatter.Get(
                    "/api/user",
                    headers={'Authorization': "Bearer %s" % token})
                info = res[0]
                username = info['username']
                api_flag = False
                ConfigModule.add_config_value(AUTHENTICATION_TAG, "username",
                                              username)
                break
            except:
                print("Incorrect API key...")
                server_name, api = zeuz_authentication_prompts_for_cli()
                continue
        else:
            print("Server down. Trying again after 30 seconds")
            time.sleep(30)

    if password == "YourUserNameGoesHere":
        password = password
    else:
        password = pass_decode("zeuz", password)

    # form payload object
    user_info_object = {
        "username": username,
        "password": password,
        "project": "",
        "team": "",
    }

    # Iniitalize GUI Offline call
    CommonUtil.set_exit_mode(False)
    global exit_script
    global processing_test_case

    exit_script = False  # Reset exit variable

    while True:
        if exit_script:
            break

        # if not user_info_object["username"] or not user_info_object["password"]:
        #    break

        # Test to ensure server is up before attempting to login
        r = check_server_online()

        # Login to server
        if r:  # Server is up
            try:
                default_team_and_project = RequestFormatter.UpdatedGet(
                    "get_default_team_and_project_api", {"username": username})

                if not default_team_and_project:
                    CommonUtil.ExecLog(
                        "AUTH FAILED",
                        "Failed to get TEAM and PROJECT information. Incorrect username or password.",
                        3,
                        False,
                    )
                    break
                user_info_object["project"] = default_team_and_project[
                    "project_name"]
                user_info_object["team"] = default_team_and_project[
                    "team_name"]

                CommonUtil.ExecLog("", f"Authenticating user: {username}", 4,
                                   False)

                if api_flag:
                    r = RequestFormatter.Post("login_api", user_info_object)

                if r or (isinstance(r, dict) and r['status'] == 200):
                    CommonUtil.ExecLog(
                        "", f"Authentication successful: USER='******', "
                        f"PROJECT='{user_info_object['project']}', TEAM='{user_info_object['team']}', SERVER='{server_name}'",
                        4)
                    ConfigModule.add_config_value("sectionOne", PROJECT_TAG,
                                                  user_info_object['project'],
                                                  temp_ini_file)
                    ConfigModule.add_config_value("sectionOne", TEAM_TAG,
                                                  user_info_object['team'],
                                                  temp_ini_file)
                    global device_dict
                    device_dict = All_Device_Info.get_all_connected_device_info(
                    )
                    machine_object = update_machine(
                        dependency_collection(default_team_and_project),
                        default_team_and_project,
                    )
                    if machine_object["registered"]:
                        tester_id = machine_object["name"]
                        try:
                            # send machine's time zone
                            local_tz = str(get_localzone())
                            time_zone_object = {
                                "time_zone": local_tz,
                                "machine": tester_id,
                            }
                            executor = CommonUtil.GetExecutor()
                            executor.submit(RequestFormatter.Get,
                                            "send_machine_time_zone_api",
                                            time_zone_object)
                            # RequestFormatter.Get("send_machine_time_zone_api", time_zone_object)
                            # end
                        except Exception as e:
                            CommonUtil.ExecLog(
                                "", "Time zone settings failed {}".format(e),
                                4, False)
                        # Telling the node_manager that the node is ready to deploy
                        CommonUtil.node_manager_json({
                            "state": "idle",
                            "report": {
                                "zip": None,
                                "directory": None,
                            }
                        })
                        run_again = RunProcess(tester_id,
                                               user_info_object,
                                               run_once=run_once,
                                               log_dir=log_dir)

                        if not run_again:
                            break  # Exit login
                    else:
                        return False
                elif not r:  # Server should send "False" when user/pass is wrong
                    CommonUtil.ExecLog(
                        "",
                        f"Authentication Failed. Username or password incorrect. SERVER='{server_name}'",
                        4,
                        False,
                    )

                    if cli:
                        zeuz_authentication_prompts_for_cli()
                        Login(cli=True)

                    break
                else:  # Server likely sent nothing back or RequestFormatter.Get() caught an exception
                    CommonUtil.ExecLog(
                        "",
                        "Login attempt failed, retrying in 60 seconds...",
                        4,
                        False,
                    )
                    if cli:
                        zeuz_authentication_prompts_for_cli()
                        Login(cli=True)
                    time.sleep(60)
            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)
                CommonUtil.ExecLog(
                    "",
                    "Error logging in, waiting 60 seconds before trying again",
                    4,
                    False,
                )
                time.sleep(60)

        # Server down, wait and retry
        else:
            CommonUtil.ExecLog(
                "",
                "Server down or verify the server address, waiting 60 seconds before trying again",
                4,
                False,
            )
            # if cli:
            #     zeuz_authentication_prompts_for_cli()
            #     Login(cli=True)
            time.sleep(60)

    if run_once:
        print(
            "[OFFLINE]",
            "Zeuz Node is going offline after running one session, since `--once` or `-o` flag is specified."
        )
    else:
        CommonUtil.ExecLog(
            "[OFFLINE]", "Zeuz Node Offline", 3
        )  # GUI relies on this exact text. GUI must be updated if this is changed

    processing_test_case = False