Exemplo n.º 1
0
	def install_packages(self, packages):
		"""
		This function will take a list of Python packages and attempt to install
		them through pip to the :py:attr:`.library_path`.

		.. versionadded:: 1.14.0

		:param list packages: list of python packages to install using pip.
		:return: The process results from the command execution.
		:rtype: :py:class:`~.ProcessResults`
		"""
		pip_options = []
		if self.library_path is None:
			raise errors.KingPhisherResourceError('missing plugin-specific library path')
		pip_options.extend(['--target', self.library_path])
		if its.frozen:
			args = [os.path.join(os.path.dirname(sys.executable), 'python.exe')]
		else:
			args = [sys.executable] + pip_options + packages
		args += ['-m', 'pip', 'install'] + pip_options + packages
		if len(packages) > 1:
			info_string = "installing packages: {}"
		else:
			info_string = "installing package: {}"
		self.logger.info(info_string.format(', '.join(packages)))
		return startup.run_process(args)
Exemplo n.º 2
0
	def _pip_install(self, packages):
		options = ['--no-color']
		if self.application.user_library_path is None:
			self.logger.warning('can not install packages with out a defined library path')
			return
		options.extend(['--target', self.application.user_library_path])
		args = [sys.executable, '-m', 'pip', 'install'] + options + packages
		return startup.run_process(args)
Exemplo n.º 3
0
 def _pip_install(self, packages):
     options = ['--no-color']
     if self.application.user_library_path is None:
         self.logger.warning(
             'can not install packages with out a defined library path')
         return
     options.extend(['--target', self.application.user_library_path])
     args = [sys.executable, '-m', 'pip', 'install'] + options + packages
     return startup.run_process(args)
Exemplo n.º 4
0
def _popen_psql(sql):
    if os.getuid():
        raise RuntimeError(
            '_popen_psql can only be used as root due to su requirement')
    results = startup.run_process(
        ['su', 'postgres', '-c', "psql -At -c \"{0}\"".format(sql)])
    if results.status != os.EX_OK:
        raise errors.KingPhisherDatabaseError(
            "failed to execute postgresql query '{0}' via su and psql".format(
                sql))
    return results.stdout.split('\n')
Exemplo n.º 5
0
def rpc_ssl_letsencrypt_certbot_version(handler):
	"""
	Find the certbot binary and retrieve it's version information. If the
	certbot binary could not be found, ``None`` is returned.

	.. versionadded:: 1.14.0

	:return: The version of certbot.
	:rtype: str
	"""
	bin_path = letsencrypt.get_certbot_bin_path(handler.config)
	if bin_path is None:
		return None
	results = startup.run_process((bin_path, '--version'))
	match = re.match(r'^certbot (?P<version>\d+\.\d+\.\d+)$', results.stdout)
	if match is None:
		return None
	return match.group('version')
Exemplo n.º 6
0
def init_database_postgresql(connection_url):
    """
	Perform additional initialization checks and operations for a PostgreSQL
	database. If the database is hosted locally this will ensure that the
	service is currently running and start it if it is not. Additionally if the
	specified database or user do not exist, they will be created.

	:param connection_url: The url for the PostgreSQL database connection.
	:type connection_url: :py:class:`sqlalchemy.engine.url.URL`
	:return: The initialized database engine.
	"""
    if not ipaddress.is_loopback(connection_url.host):
        return

    is_sanitary = lambda s: re.match(r'^[a-zA-Z0-9_]+$', s) is not None

    systemctl_bin = smoke_zephyr.utilities.which('systemctl')
    if systemctl_bin is None:
        logger.info(
            'postgresql service status check failed (could not find systemctl)'
        )
    else:
        postgresql_setup = smoke_zephyr.utilities.which('postgresql-setup')
        if postgresql_setup is None:
            logger.debug('postgresql-setup was not found')
        else:
            logger.debug(
                'using postgresql-setup to ensure that the database is initialized'
            )
            startup.run_process([postgresql_setup, '--initdb'])
        results = startup.run_process(
            [systemctl_bin, 'status', 'postgresql.service'])
        # wait for the process to return and check if it's running (status 0)
        if results.status == os.EX_OK:
            logger.debug('postgresql service is already running via systemctl')
        else:
            logger.info(
                'postgresql service is not running, starting it now via systemctl'
            )
            results = startup.run_process(
                [systemctl_bin, 'start', 'postgresql'])
            if results.status != os.EX_OK:
                logger.error(
                    'failed to start the postgresql service via systemctl')
                raise errors.KingPhisherDatabaseError(
                    'postgresql service failed to start via systemctl')
            logger.debug(
                'postgresql service successfully started via systemctl')

    rows = _popen_psql('SELECT usename FROM pg_user')
    if connection_url.username not in rows:
        logger.info(
            'the specified postgresql user does not exist, adding it now')
        if not is_sanitary(connection_url.username):
            raise errors.KingPhisherInputValidationError(
                'will not create the postgresql user (username contains bad characters)'
            )
        if not is_sanitary(connection_url.password):
            raise errors.KingPhisherInputValidationError(
                'will not create the postgresql user (password contains bad characters)'
            )
        rows = _popen_psql(
            "CREATE USER {url.username} WITH PASSWORD '{url.password}'".format(
                url=connection_url))
        if rows != ['CREATE ROLE']:
            logger.error('failed to create the postgresql user')
            raise errors.KingPhisherDatabaseError(
                'failed to create the postgresql user')
        logger.debug('the specified postgresql user was successfully created')

    rows = _popen_psql('SELECT datname FROM pg_database')
    if connection_url.database not in rows:
        logger.info(
            'the specified postgresql database does not exist, adding it now')
        if not is_sanitary(connection_url.database):
            raise errors.KingPhisherInputValidationError(
                'will not create the postgresql database (name contains bad characters)'
            )
        rows = _popen_psql(
            "CREATE DATABASE {url.database} OWNER {url.username}".format(
                url=connection_url))
        if rows != ['CREATE DATABASE']:
            logger.error('failed to create the postgresql database')
            raise errors.KingPhisherDatabaseError(
                'failed to create the postgresql database')
        logger.debug(
            'the specified postgresql database was successfully created')
Exemplo n.º 7
0
def _run_certbot(args, bin_path=None):
    bin_path = bin_path or get_certbot_bin_path()
    if bin_path is None:
        return FileNotFoundError('the certbot binary could not be found')
    args = (bin_path, ) + tuple(args)
    return startup.run_process(args)