Example #1
0
async def async_get_system_info(opp: OpenPeerPower) -> dict[str, Any]:
    """Return info about the system."""
    info_object = {
        "installation_type": "Unknown",
        "version": current_version,
        "dev": "dev" in current_version,
        "oppio": opp.components.oppio.is_oppio(),
        "virtualenv": is_virtual_env(),
        "python_version": platform.python_version(),
        "docker": False,
        "arch": platform.machine(),
        "timezone": str(opp.config.time_zone),
        "os_name": platform.system(),
        "os_version": platform.release(),
    }

    if platform.system() == "Windows":
        info_object["os_version"] = platform.win32_ver()[0]
    elif platform.system() == "Darwin":
        info_object["os_version"] = platform.mac_ver()[0]
    elif platform.system() == "Linux":
        info_object["docker"] = os.path.isfile("/.dockerenv")

    # Determine installation type on current data
    if info_object["docker"]:
        info_object["installation_type"] = "Open Peer Power Container"
    elif is_virtual_env():
        info_object["installation_type"] = "Open Peer Power Core"

    # Enrich with Supervisor information
    if opp.components.oppio.is_oppio():
        info = opp.components.oppio.get_info()
        host = opp.components.oppio.get_host_info()

        info_object["supervisor"] = info.get("supervisor")
        info_object["host_os"] = host.get("operating_system")
        info_object["docker_version"] = info.get("docker")
        info_object["copp.s"] = host.get("copp.s")

        if info.get("oppos") is not None:
            info_object["installation_type"] = "Open Peer Power OS"
        else:
            info_object["installation_type"] = "Open Peer Power Supervised"

    return info_object
Example #2
0
def pip_kwargs(config_dir: str | None) -> dict[str, Any]:
    """Return keyword arguments for PIP install."""
    is_docker = pkg_util.is_docker_env()
    kwargs = {
        "constraints": os.path.join(os.path.dirname(__file__),
                                    CONSTRAINT_FILE),
        "no_cache_dir": is_docker,
    }
    if "WHEELS_LINKS" in os.environ:
        kwargs["find_links"] = os.environ["WHEELS_LINKS"]
    if not (config_dir is None or pkg_util.is_virtual_env()) and not is_docker:
        kwargs["target"] = os.path.join(config_dir, "deps")
    return kwargs
Example #3
0
def run(args: list) -> int:
    """Run a script."""
    scripts = []
    path = os.path.dirname(__file__)
    for fil in os.listdir(path):
        if fil == "__pycache__":
            continue

        if os.path.isdir(os.path.join(path, fil)):
            scripts.append(fil)
        elif fil != "__init__.py" and fil.endswith(".py"):
            scripts.append(fil[:-3])

    if not args:
        print("Please specify a script to run.")
        print("Available scripts:", ", ".join(scripts))
        return 1

    if args[0] not in scripts:
        print("Invalid script specified.")
        print("Available scripts:", ", ".join(scripts))
        return 1

    script = importlib.import_module(f"openpeerpower.scripts.{args[0]}")

    config_dir = extract_config_dir()

    loop = asyncio.get_event_loop()

    if not is_virtual_env():
        loop.run_until_complete(async_mount_local_lib_path(config_dir))

    _pip_kwargs = pip_kwargs(config_dir)

    logging.basicConfig(stream=sys.stdout, level=logging.INFO)

    for req in getattr(script, "REQUIREMENTS", []):
        if is_installed(req):
            continue

        if not install_package(req, **_pip_kwargs):
            print("Aborting script, could not install dependency", req)
            return 1

    asyncio.set_event_loop_policy(runner.OppEventLoopPolicy(False))

    return script.run(args[1:])  # type: ignore
Example #4
0
async def async_get_system_info(opp: OpenPeerPowerType) -> Dict:
    """Return info about the system."""
    info_object = {
        "version": current_version,
        "dev": "dev" in current_version,
        "oppio": opp.components.oppio.is_oppio(),
        "virtualenv": is_virtual_env(),
        "python_version": platform.python_version(),
        "docker": False,
        "arch": platform.machine(),
        "timezone": str(opp.config.time_zone),
        "os_name": platform.system(),
    }

    if platform.system() == "Windows":
        info_object["os_version"] = platform.win32_ver()[0]
    elif platform.system() == "Darwin":
        info_object["os_version"] = platform.mac_ver()[0]
    elif platform.system() == "FreeBSD":
        info_object["os_version"] = platform.release()
    elif platform.system() == "Linux":
        info_object["docker"] = os.path.isfile("/.dockerenv")

    return info_object
async def async_setup_opp(
    *,
    config_dir: str,
    verbose: bool,
    log_rotate_days: int,
    log_file: str,
    log_no_color: bool,
    skip_pip: bool,
    safe_mode: bool,
) -> Optional[core.OpenPeerPower]:
    """Set up Open Peer Power."""
    opp = core.OpenPeerPower()
    opp.config.config_dir = config_dir

    async_enable_logging(opp, verbose, log_rotate_days, log_file, log_no_color)

    opp.config.skip_pip = skip_pip
    if skip_pip:
        _LOGGER.warning(
            "Skipping pip installation of required modules. This may cause issues"
        )

    if not await conf_util.async_ensure_config_exists(opp):
        _LOGGER.error("Error getting configuration path")
        return None

    _LOGGER.info("Config directory: %s", config_dir)

    config_dict = None
    basic_setup_success = False

    if not safe_mode:
        await opp.async_add_executor_job(conf_util.process_op_config_upgrade, opp)

        try:
            config_dict = await conf_util.async_opp_config_yaml(opp)
        except OpenPeerPowerError as err:
            _LOGGER.error(
                "Failed to parse configuration.yaml: %s. Activating safe mode",
                err,
            )
        else:
            if not is_virtual_env():
                await async_mount_local_lib_path(config_dir)

            basic_setup_success = (
                await async_from_config_dict(config_dict, opp) is not None
            )
        finally:
            clear_secret_cache()

    if config_dict is None:
        safe_mode = True

    elif not basic_setup_success:
        _LOGGER.warning("Unable to set up core integrations. Activating safe mode")
        safe_mode = True

    elif (
        "frontend" in opp.data.get(DATA_SETUP, {})
        and "frontend" not in opp.config.components
    ):
        _LOGGER.warning("Detected that frontend did not load. Activating safe mode")
        # Ask integrations to shut down. It's messy but we can't
        # do a clean stop without knowing what is broken
        opp.async_track_tasks()
        opp.bus.async_fire(EVENT_OPENPEERPOWER_STOP, {})
        with contextlib.suppress(asyncio.TimeoutError):
            async with timeout(10):
                await opp.async_block_till_done()

        safe_mode = True
        opp = core.OpenPeerPower()
        opp.config.config_dir = config_dir

    if safe_mode:
        _LOGGER.info("Starting in safe mode")
        opp.config.safe_mode = True

        http_conf = (await http.async_get_last_config(opp)) or {}

        await async_from_config_dict(
            {"safe_mode": {}, "http": http_conf},
            opp,
        )

    return opp
Example #6
0
async def async_setup_opp(
    runtime_config: RuntimeConfig, ) -> core.OpenPeerPower | None:
    """Set up Open Peer Power."""
    opp = core.OpenPeerPower()
    opp.config.config_dir = runtime_config.config_dir

    async_enable_logging(
        opp,
        runtime_config.verbose,
        runtime_config.log_rotate_days,
        runtime_config.log_file,
        runtime_config.log_no_color,
    )

    opp.config.skip_pip = runtime_config.skip_pip
    if runtime_config.skip_pip:
        _LOGGER.warning(
            "Skipping pip installation of required modules. This may cause issues"
        )

    if not await conf_util.async_ensure_config_exists(opp):
        _LOGGER.error("Error getting configuration path")
        return None

    _LOGGER.info("Config directory: %s", runtime_config.config_dir)

    config_dict = None
    basic_setup_success = False
    safe_mode = runtime_config.safe_mode

    if not safe_mode:
        await opp.async_add_executor_job(conf_util.process_op_config_upgrade,
                                         opp)

        try:
            config_dict = await conf_util.async_opp_config_yaml(opp)
        except OpenPeerPowerError as err:
            _LOGGER.error(
                "Failed to parse configuration.yaml: %s. Activating safe mode",
                err,
            )
        else:
            if not is_virtual_env():
                await async_mount_local_lib_path(runtime_config.config_dir)

            basic_setup_success = (await
                                   async_from_config_dict(config_dict,
                                                          opp) is not None)

    if config_dict is None:
        safe_mode = True

    elif not basic_setup_success:
        _LOGGER.warning(
            "Unable to set up core integrations. Activating safe mode")
        safe_mode = True

    elif ("frontend" in opp.data.get(DATA_SETUP, {})
          and "frontend" not in opp.config.components):
        _LOGGER.warning(
            "Detected that frontend did not load. Activating safe mode")
        # Ask integrations to shut down. It's messy but we can't
        # do a clean stop without knowing what is broken
        with contextlib.suppress(asyncio.TimeoutError):
            async with opp.timeout.async_timeout(10):
                await opp.async_stop()

        safe_mode = True
        old_config = opp.config

        opp = core.OpenPeerPower()
        opp.config.skip_pip = old_config.skip_pip
        opp.config.internal_url = old_config.internal_url
        opp.config.external_url = old_config.external_url
        opp.config.config_dir = old_config.config_dir

    if safe_mode:
        _LOGGER.info("Starting in safe mode")
        opp.config.safe_mode = True

        http_conf = (await http.async_get_last_config(opp)) or {}

        await async_from_config_dict(
            {
                "safe_mode": {},
                "http": http_conf
            },
            opp,
        )

    if runtime_config.open_ui:
        opp.add_job(open_opp_ui, opp)

    return opp