Esempio n. 1
0
def zeuz_authentication_prompts_for_cli():
    prompts = ["server_address", "api-key"]
    values = []
    for prompt in prompts:
        if prompt == "password":
            value = getpass()
            ConfigModule.add_config_value(AUTHENTICATION_TAG, prompt,
                                          password_hash(False, "zeuz", value))
        else:
            display_text = prompt.replace("_", " ").capitalize()
            value = input(f"{display_text}: ")
            if prompt == "server_address":
                if value[-1] == "/":
                    value = value[:-1]
            ConfigModule.add_config_value(AUTHENTICATION_TAG, prompt,
                                          str(value))
        values.append(value)
    return values
    def getLocalUser(self):
        """
        :return: returns the local pc name
        """
        try:
            # node_id_file_path = os.path.join(FL.get_home_folder(), os.path.join('Desktop', 'node_id.conf'))
            # node_id_file_path = os.path.join (os.path.realpath(__file__).split("Framework")[0] , os.path.join ('node_id.conf'))

            node_id_file_path = Path(
                os.path.abspath(__file__).split("Framework")[0]) / Path(
                    "node_id.conf")

            if os.path.isfile(node_id_file_path):
                unique_id = ConfigModule.get_config_value(
                    "UniqueID", "id", node_id_file_path)
                if unique_id == "":
                    ConfigModule.clean_config_file(node_id_file_path)
                    ConfigModule.add_section("UniqueID", node_id_file_path)
                    unique_id = uuid.uuid4()
                    unique_id = str(unique_id)[:10]
                    ConfigModule.add_config_value("UniqueID", "id", unique_id,
                                                  node_id_file_path)
                    machine_name = (ConfigModule.get_config_value(
                        "Authentication", "username") + "_" + str(unique_id))
                    return machine_name[:100]
                machine_name = (ConfigModule.get_config_value(
                    "Authentication", "username") + "_" + str(unique_id))
            else:
                # create the file name
                f = open(node_id_file_path, "w")
                f.close()
                unique_id = uuid.uuid4()
                unique_id = str(unique_id).lower()[:10]
                ConfigModule.add_section("UniqueID", node_id_file_path)
                ConfigModule.add_config_value("UniqueID", "id", unique_id,
                                              node_id_file_path)
                machine_name = (ConfigModule.get_config_value(
                    "Authentication", "username") + "_" + str(unique_id))
            return machine_name[:100]

        except Exception:
            ErrorMessage = "Unable to set create a Node key.  Please check class MachineInfo() in commonutil"
            return Exception_Handler(sys.exc_info(), None, ErrorMessage)
def update():
    try:
        path = ChromeDriverManager().install()
        print("Downloaded Chrome driver into:", path)
        ConfigModule.add_config_value("Selenium_driver_paths", "chrome_path",
                                      path, location)
    except:
        print(sys.exc_info())

    try:
        path = GeckoDriverManager().install()
        print("Downloaded Firefox driver into:", path)
        ConfigModule.add_config_value("Selenium_driver_paths", "firefox_path",
                                      path, location)
    except:
        print(sys.exc_info())

    try:
        path = EdgeChromiumDriverManager().install()
        print("Downloaded Edge driver into:", path)
        ConfigModule.add_config_value("Selenium_driver_paths", "edge_path",
                                      path, location)
    except:
        print(sys.exc_info())

    try:
        path = OperaDriverManager().install()
        print("Downloaded Opera driver into:", path)
        ConfigModule.add_config_value("Selenium_driver_paths", "opera_path",
                                      path, location)
    except:
        print(sys.exc_info())

    try:
        path = IEDriverManager().install()
        print("Downloaded Internet Explorer driver into:", path)
        ConfigModule.add_config_value("Selenium_driver_paths", "ie_path", path,
                                      location)
    except:
        print(sys.exc_info())
    def getUniqueId(self):
        """
        This function is not used any more
        :return: returns the local pc unique ID
        """
        try:
            node_id_file_path = Path(
                os.path.abspath(__file__).split("Framework")[0]) / Path(
                    "node_id.conf")

            if os.path.isfile(node_id_file_path):
                unique_id = ConfigModule.get_config_value(
                    "UniqueID", "id", node_id_file_path)
                if unique_id == "":
                    ConfigModule.clean_config_file(node_id_file_path)
                    ConfigModule.add_section("UniqueID", node_id_file_path)
                    unique_id = uuid.uuid4()
                    unique_id = str(unique_id)[:10]
                    ConfigModule.add_config_value("UniqueID", "id", unique_id,
                                                  node_id_file_path)
                    machine_name = str(unique_id)
                    return machine_name[:100]
                machine_name = str(unique_id)
            else:
                # create the file name
                f = open(node_id_file_path, "w")
                f.close()
                unique_id = uuid.uuid4()
                unique_id = str(unique_id)[:10]
                ConfigModule.add_section("UniqueID", node_id_file_path)
                ConfigModule.add_config_value("UniqueID", "id", unique_id,
                                              node_id_file_path)
                machine_name = str(unique_id)
            return machine_name[:100]

        except Exception:
            ErrorMessage = "Unable to set create a Node key.  Please check class MachineInfo() in commonutil"
            return Exception_Handler(sys.exc_info(), None, ErrorMessage)
 def setLocalUser(self, custom_id):
     """
     Set node_id from node_cli Command Line Interface and returns local userid
     """
     try:
         node_id_file_path = Path(
             os.path.abspath(__file__).split("Framework")
             [0]) / "node_id.conf"
         if os.path.isfile(node_id_file_path):
             ConfigModule.clean_config_file(node_id_file_path)
             ConfigModule.add_section("UniqueID", node_id_file_path)
             custom_id = custom_id.lower()[:10]
             ConfigModule.add_config_value("UniqueID", "id", custom_id,
                                           node_id_file_path)
         else:
             f = open(node_id_file_path, "w")
             f.close()
             ConfigModule.add_section("UniqueID", node_id_file_path)
             custom_id = custom_id.lower()[:10]
             ConfigModule.add_config_value("UniqueID", "id", custom_id,
                                           node_id_file_path)
     except Exception:
         ErrorMessage = "Unable to set create a Node key.  Please check class MachineInfo() in commonutil"
         return Exception_Handler(sys.exc_info(), None, ErrorMessage)
Esempio n. 6
0
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
Esempio n. 7
0
def PreProcess(log_dir=None):
    current_path_file = temp_ini_file
    ConfigModule.clean_config_file(current_path_file)
    ConfigModule.add_section("sectionOne", current_path_file)

    if not ConfigModule.has_section("Selenium_driver_paths"):
        ConfigModule.add_section("Selenium_driver_paths")
        ConfigModule.add_config_value("Selenium_driver_paths", "chrome_path",
                                      "")
        ConfigModule.add_config_value("Selenium_driver_paths", "firefox_path",
                                      "")
        ConfigModule.add_config_value("Selenium_driver_paths", "edge_path", "")
        ConfigModule.add_config_value("Selenium_driver_paths", "opera_path",
                                      "")
        ConfigModule.add_config_value("Selenium_driver_paths", "ie_path", "")
    if not ConfigModule.get_config_value("Selenium_driver_paths",
                                         "electron_chrome_path"):
        ConfigModule.add_config_value("Selenium_driver_paths",
                                      "electron_chrome_path", "")

    # If `log_dir` is not specified, then store all logs inside Zeuz Node's
    # "AutomationLog" folder
    if log_dir is None:
        log_dir = temp_ini_file.parent

    ConfigModule.add_config_value(
        "sectionOne",
        "temp_run_file_path",
        str(log_dir),
        current_path_file,
    )
    ConfigModule.add_config_value("sectionOne", "sTestStepExecLogId",
                                  "node_cli", temp_ini_file)
Esempio n. 8
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
def set_exit_mode(emode):
    """ Sets a value in the temp config file to tell sequential actions to exit, if set to true """
    # Set by the user via the GUI
    ConfigModule.add_config_value("sectionOne", "exit_script", str(emode),
                                  temp_config)