示例#1
0
def install_webapplication(restart=False):
    """
    Install the web application component to a Raspberry PI.
    """
    ssh = get_connection()

    execute_remote(
        message="Delete old webapplication on remote site...",
        ssh=ssh,
        command="rm -R server/webapplication || true",
    )

    target = join("server", "webapplication")
    logger.info("Copy web application: %s => %s",
                CONFIG["webapplication_path"], target)
    deep_copy(ssh, CONFIG["webapplication_path"], target, "**/*",
              CONFIG["progress"])

    if restart:
        execute_remote(
            message="Restarting the service...",
            ssh=ssh,
            command="sudo systemctl restart argus_server.service",
        )
示例#2
0
def play_a_level(board):
    """Take a board, a list of lists.  Guides the user through a level of
    "Lights out!".

    Sideffects include I/O with the user and modifying the board.

    Return the amount of points scored by the user as a integer.
    """
    def input_condition(i):
        return (2 <= len(i) <= 3 and i[1:].isdigit() and utils.is_sane_point_choice(i, len(board)-1))\
                or (i == 'RESET')

    original_board = utils.deep_copy(board)  # keep one in case user resets
    turns_available = len(board)*3
    points_scored = 0
    for _ in range(turns_available):
        print(str_board(board))
        game_choice = utils.game_input([input_condition],
                                       ["A1", "B6", "D9", "C4"],
                                       ["Please input the light you'd like to switch",
                                        "For example, A1 for the top leftmost light",
                                        "No spaces please. Input RESET to reset the level"])
        if game_choice.upper() == "RESET":
            print("Remember that reseting will cost you 50 times the number of lights you've got turned on!")
            points_scored -= 50 * amount_of_lights_turned_on(board)
            board = original_board
            continue
        point = game_choice  # if the user didnt reset, this is a point on the board
        x, y = (utils.letter_to_int(point[0]), int(point[1])-1)
        change_board(x, y, board)  # mod board to reflect user decision
        turns_available -= 1
        if success(board):
            points_scored += 500
            print("Wohooo! You made it! +500 points!")
            return points_scored
    else:
        print("Boooh, you lost! 300 points lost!")
        points_scored -= 300
        return points_scored
示例#3
0
def install_environment():
    """
    Install prerequisites to an empty Raspberry PI.
    """
    if not exists(CONFIG["arpi_key_name"]) and \
       not exists(CONFIG["arpi_key_name"] + ".pub"):
        generate_SSH_key(CONFIG["arpi_key_name"], CONFIG["arpi_password"])

    dhparam_file = "arpi_dhparam.pem"
    if not exists(dhparam_file):
        logger.info("dhparam (%s) generating", dhparam_file)
        system(f"openssl dhparam -out {dhparam_file} {CONFIG['dhparam_size']}")
    else:
        logger.info("dhparam (%s) already exists", dhparam_file)
        system(f"openssl dhparam -in {dhparam_file} -text | head -3")

    # create the env variables string because paramiko update_evironment ignores them
    arguments = {
        "ARPI_PASSWORD": CONFIG["arpi_password"],
        "ARGUS_DB_SCHEMA": CONFIG["argus_db_schema"],
        "ARGUS_DB_USERNAME": CONFIG["argus_db_username"],
        "ARGUS_DB_PASSWORD": CONFIG["argus_db_password"],
        "ARPI_HOSTNAME": CONFIG["arpi_hostname"],
        "DHPARAM_FILE": join("/tmp", dhparam_file),
        # progress
        "QUIET": "" if CONFIG["progress"] else "-q",
        "PROGRESS": "on" if CONFIG["progress"] else "off"
    }

    # adding package versions
    arguments.update(
        {p.upper(): f"{v}"
         for p, v in CONFIG["packages"].items() if v})

    arguments = [f"export {key}={value}" for key, value in arguments.items()]
    arguments = "; ".join(arguments)

    ssh = get_connection()
    scp = SCPClient(ssh.get_transport(),
                    progress=show_progress if CONFIG["progress"] else None)
    scp.put("scripts/install_environment.sh", remote_path=".")
    deep_copy(ssh, join(CONFIG["server_path"], "etc"), "/tmp/etc", "**/*",
              CONFIG["progress"])
    list_copy(ssh, ((dhparam_file, "/tmp"), ), CONFIG["progress"])

    channel = ssh.get_transport().open_session()
    channel.get_pty()
    channel.set_combine_stderr(True)
    output = channel.makefile("r", -1)

    logger.info("Starting install script...")
    channel.exec_command(f"{arguments}; ./install_environment.sh")
    print_lines(output)
    ssh.close()

    # waiting for user
    # 1. deploy key can timeout
    # 2. ssh accept password only from terminal
    input("Waiting before deploying public key!")
    command = f"ssh-copy-id -i {CONFIG['arpi_key_name']} {CONFIG['arpi_username']}@{CONFIG['default_hostname']}"
    logger.info("Deploy public key: %s", command)
    while subprocess.call(command, shell=True) != 0:
        # retry after 2 seconds
        sleep(2)

    ssh = get_connection()

    execute_remote(
        message="Enabling key based ssh authentication",
        ssh=ssh,
        command=
        "sudo sed -i -E -e 's/.*PasswordAuthentication (yes|no)/PasswordAuthentication no/g' /etc/ssh/sshd_config",
    )

    execute_remote(message="Restarting the host",
                   ssh=ssh,
                   command="sudo reboot")
示例#4
0
def create_random_of_dimension(n):
    """Return a random board of dimension n"""
    return deep_copy([[choice([True, False]) for _ in range(n)] for row in range(n)])
示例#5
0
def install_component(component, update=False, restart=False):
    """
    Install the monitor component to a Raspberry PI.
    """
    ssh = get_connection()

    execute_remote(
        message="Creating server directories...",
        ssh=ssh,
        command=
        "mkdir -p  server/etc server/scripts server/src server/webapplication",
    )

    logger.info("Copy common files...")
    list_copy(ssh, (
        (join(CONFIG["server_path"], "Pipfile"), "server"),
        (join(CONFIG["server_path"], "Pipfile.lock"), "server"),
        (join(CONFIG["server_path"],
              f".env_{CONFIG['environment']}"), "server/.env"),
        (join(CONFIG["server_path"], "src",
              "data.py"), join("server", "src", "data.py")),
        (join(CONFIG["server_path"], "src",
              "hash.py"), join("server", "src", "hash.py")),
        (join(CONFIG["server_path"], "src",
              "models.py"), join("server", "src", "models.py")),
    ), CONFIG["progress"])
    deep_copy(ssh, join(CONFIG["server_path"], "src", "tools"),
              join("server", "src", "tools"), "**/*.py", CONFIG["progress"])

    logger.info("Copy component '%s'...", component)
    deep_copy(ssh, join(CONFIG["server_path"], "src", component),
              join("server", "src", component), "**/*.py", CONFIG["progress"])

    if update:
        execute_remote(
            message="Start installing python packages on sytem...",
            ssh=ssh,
            command=
            "cd server; sudo PIPENV_TIMEOUT=9999 pipenv install --system",
        )
        execute_remote(
            message="Create virtual environment with python3 for argus...",
            ssh=ssh,
            command=
            "cd server; PIPENV_TIMEOUT=9999 CI=1 pipenv install --skip-lock --site-packages",
        )
        execute_remote(
            message="Create virtual environment with python3 for root...",
            ssh=ssh,
            command=
            "cd server; sudo PIPENV_TIMEOUT=9999 CI=1 pipenv install --skip-lock --site-packages",
        )

    if restart:
        execute_remote(
            message="Restarting the service...",
            ssh=ssh,
            command=
            "sudo systemctl restart argus_monitor.service argus_server.service",
        )

    ssh.close()
示例#6
0
def get_fifth():
    """Return a copy of the board for the fifth level."""
    return deep_copy(_FIVE)
示例#7
0
def get_fourth():
    """Return a copy of the board for the fourth level."""
    return deep_copy(_FOUR)
示例#8
0
def get_third():
    """Return a copy of the board for the third level."""
    return deep_copy(_THREE)
示例#9
0
def get_second():
    """Return a copy of the board for the second level."""
    return deep_copy(_TWO)
示例#10
0
def get_first():
    """Return a copy of the board for the first level."""
    return deep_copy(_ONE)