Python os.EX_OK Examples

The following are 29 code examples of os.EX_OK(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: test.py    From aegea with Apache License 2.0 16 votes vote down vote up
def call(self, cmd, **kwargs):
        print('Running "{}"'.format(cmd), file=sys.stderr)
        expect = kwargs.pop("expect", [dict(return_codes=[os.EX_OK], stdout=None, stderr=None)])
        process = subprocess.Popen(cmd, stdin=kwargs.get("stdin", subprocess.PIPE), stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE, **kwargs)
        out, err = process.communicate()
        return_code = process.poll()
        out = out.decode(sys.stdin.encoding)
        err = err.decode(sys.stdin.encoding)

        def match(return_code, out, err, expected):
            exit_ok = return_code in expected["return_codes"]
            stdout_ok = re.search(expected.get("stdout") or "", out)
            stderr_ok = re.search(expected.get("stderr") or "", err)
            return exit_ok and stdout_ok and stderr_ok
        if not any(match(return_code, out, err, exp) for exp in expect):
            print(err)
            e = subprocess.CalledProcessError(return_code, cmd, output=out)
            e.stdout, e.stderr = out, err
            raise e
        return self.SubprocessResult(out, err, return_code) 
Example #2
Source File: typecheck.py    From temci with GNU General Public License v3.0 6 votes vote down vote up
def _instancecheck_impl(self, value, info: Info) -> InfoMsg:
        if not isinstance(value, str) or value == "":
            return info.errormsg(self, value)
        value = os.path.expanduser(value)
        if self.allow_std and value == "-" and (self.constraint is None or self.constraint(value)):
            return info.wrap(True)
        is_valid = True
        if os.path.exists(value):
            if os.path.isfile(value) and os.access(os.path.abspath(value), os.W_OK)\
                    and (self.constraint is None or self.constraint(value)):
                return info.wrap(True)
            return info.errormsg(self, value)
        if not self.allow_non_existent:
            return info.errormsg(self, "File doesn't exist")
        abs_name = os.path.abspath(value)
        dir_name = os.path.dirname(abs_name)
        if os.path.exists(dir_name) and os.access(dir_name, os.EX_OK) and os.access(dir_name, os.W_OK) \
            and (self.constraint is None or self.constraint(value)):
            return info.wrap(True)
        return info.errormsg(self, value) 
Example #3
Source File: daemon.py    From concierge with MIT License 6 votes vote down vote up
def manage_events(self, notify):
        filename = os.path.basename(self.source_path)

        while True:
            try:
                events = notify.read()
            except KeyboardInterrupt:
                return os.EX_OK
            else:
                LOG.debug("Caught %d events", len(events))

            events = self.filter_events(filename, events)
            descriptions = self.describe_events(events)
            LOG.debug("Got %d events after filtration: %s",
                      len(descriptions), descriptions)

            if events:
                self.output()

            LOG.info("Config was managed. Going to the next loop.") 
Example #4
Source File: ceph_version.py    From ceph-lcm with Apache License 2.0 6 votes vote down vote up
def get_package_version(prefix, connection, package_name):
    command = "dpkg-query --showformat='${Version}' --show %s" % shlex.quote(
        package_name)
    result = await connection.run(command)

    if result.exit_status != os.EX_OK:
        click.echo(
            "{0}package (failed {1}): {2} - {3}".format(
                prefix, result.exit_status, package_name, result.stderr.strip()
            )
        )
    else:
        click.echo(
            "{0}package (ok): {1}=={2}".format(
                prefix, package_name, result.stdout.strip()
            )
        ) 
Example #5
Source File: test.py    From aegea with Apache License 2.0 6 votes vote down vote up
def test_dry_run_commands(self):
        unauthorized_ok = [dict(return_codes=[os.EX_OK]),
                           dict(return_codes=[1, os.EX_SOFTWARE], stderr="UnauthorizedOperation")]
        self.call("aegea launch unittest --dry-run --storage /x=512 /y=1024 --ubuntu-linux-ami",
                  shell=True, expect=unauthorized_ok)
        self.call("aegea launch unittest --dry-run --no-verify-ssh-key-pem-file --ubuntu-linux-ami",
                  shell=True, expect=unauthorized_ok)
        self.call("aegea launch unittest --dry-run --spot --no-verify-ssh-key-pem-file --amazon-linux-ami",
                  shell=True, expect=unauthorized_ok)
        self.call("aegea launch unittest --dry-run --duration-hours 1 --no-verify-ssh-key-pem-file --amazon-linux-ami",
                  shell=True, expect=unauthorized_ok)
        self.call(("aegea launch unittest --duration 0.5 --min-mem 6 --cores 2 --dry-run --no-verify --client-token t "
                   "--amazon-linux-ami"),
                  shell=True, expect=unauthorized_ok)
        self.call("aegea build-ami i --dry-run --no-verify-ssh-key-pem-file",
                  shell=True, expect=unauthorized_ok)

        self.call("aegea batch submit --command pwd --dry-run", shell=True)
        self.call("echo pwd > run.sh && aegea batch submit --execute run.sh --dry-run", shell=True)
        self.call("aegea batch submit --wdl '{}' --dry-run".format(__file__.replace(".py", ".wdl")), shell=True)

        self.call("aegea ecs run --command pwd --dry-run", shell=True) 
Example #6
Source File: logs.py    From aegea with Apache License 2.0 6 votes vote down vote up
def filter(args):
    filter_args = dict(logGroupName=args.log_group)
    if args.log_stream:
        filter_args.update(logStreamNames=[args.log_stream])
    if args.pattern:
        filter_args.update(filterPattern=args.pattern)
    if args.start_time:
        filter_args.update(startTime=int(timestamp(args.start_time) * 1000))
    if args.end_time:
        filter_args.update(endTime=int(timestamp(args.end_time) * 1000))
    num_results = 0
    while True:
        for event in paginate(clients.logs.get_paginator("filter_log_events"), **filter_args):
            if "timestamp" not in event or "message" not in event:
                continue
            print_log_event(event)
            num_results += 1
        if args.follow:
            time.sleep(1)
        else:
            return SystemExit(os.EX_OK if num_results > 0 else os.EX_DATAERR) 
Example #7
Source File: migration.py    From ceph-lcm with Apache License 2.0 6 votes vote down vote up
def run(self):
        if self.finished:
            return

        self.process = subprocess.Popen(
            [str(self.path)],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            shell=True
        )

        LOG.info("Run %s. Pid %d", self.path, self.process.pid)
        self.process.wait()
        logmethod = LOG.info if self.process.returncode == os.EX_OK \
            else LOG.warning
        logmethod("%s has been finished. Exit code %s",
                  self.path, self.process.returncode)

        self.stdout = self.process.stdout.read().decode("utf-8")
        self.stderr = self.process.stderr.read().decode("utf-8")

        if self.process.returncode != os.EX_OK:
            raise RuntimeError(
                "Program {0} has been finished with exit code {1}",
                self.path, self.process.returncode) 
Example #8
Source File: test_inventory.py    From ceph-lcm with Apache License 2.0 6 votes vote down vote up
def test_main_list(monkeypatch, capsys, mocked_sysexit, mocked_configure):
    server_id = pytest.faux.gen_uuid()
    host = pytest.faux.gen_alphanumeric()
    username = pytest.faux.gen_alphanumeric()
    initiator_id = pytest.faux.gen_uuid()

    tsk = task.ServerDiscoveryTask(server_id, host, username, initiator_id)
    tsk = tsk.create()

    monkeypatch.setenv(process.ENV_ENTRY_POINT, "server_discovery")
    monkeypatch.setenv(process.ENV_TASK_ID, str(tsk._id))
    monkeypatch.setattr("sys.argv", ["progname", "--list"])

    assert inventory.main() == os.EX_OK

    mocked_sysexit.assert_not_called()

    out, _ = capsys.readouterr()
    arg = json.loads(out)
    assert arg["new"]["hosts"] == [host]
    assert arg["_meta"]["hostvars"][host]["ansible_user"] == username 
Example #9
Source File: test_inventory.py    From ceph-lcm with Apache License 2.0 6 votes vote down vote up
def test_main_host_ok(monkeypatch, capsys, mocked_sysexit, mocked_configure):
    server_id = pytest.faux.gen_uuid()
    host = pytest.faux.gen_alphanumeric()
    username = pytest.faux.gen_alphanumeric()
    initiator_id = pytest.faux.gen_uuid()

    tsk = task.ServerDiscoveryTask(server_id, host, username, initiator_id)
    tsk = tsk.create()

    monkeypatch.setenv(process.ENV_ENTRY_POINT, "server_discovery")
    monkeypatch.setenv(process.ENV_TASK_ID, str(tsk._id))
    monkeypatch.setattr("sys.argv", ["progname", "--host", host])

    assert inventory.main() == os.EX_OK

    mocked_sysexit.assert_not_called()

    out, _ = capsys.readouterr()
    arg = json.loads(out)
    assert arg["ansible_user"] == username 
Example #10
Source File: test_process.py    From ceph-lcm with Apache License 2.0 5 votes vote down vote up
def test_command_result_running(proc):
    proc.options["-c"] = "import time; time.sleep(2)"
    result = proc.run()

    assert result.pid
    assert result.returncode is None
    assert result.alive()
    assert str(result)
    assert repr(result)

    time.sleep(3.5)

    assert result.pid
    assert result.returncode == os.EX_OK
    assert not result.alive() 
Example #11
Source File: pyversions.py    From pyviennacl-dev with MIT License 5 votes vote down vote up
def main(argv):
    if len(argv) < 2:
        do_help()
        return os.EX_CONFIG

    if argv[1] == "python":
        print("%d.%d.%d" % (sys.version_info.major,
                            sys.version_info.minor,
                            sys.version_info.micro))
    elif argv[1] == "boost":
        if 'linux' in platform.system().lower():
            if platform.linux_distribution()[0] == 'Ubuntu':
                print("python-py%d%d" %
                      (sys.version_info.major,
                       sys.version_info.minor))
                return os.EX_OK
            if sys.version_info == 3:
                print("python3")
            else:
                print("python")
        elif 'windows' in platform.system().lower():
            print("python")
        elif 'darwin' in platform.system().lower():
            print("python")

    else:
        do_help()
        return os.EX_CONFIG

    return os.EX_OK 
Example #12
Source File: test_taskpool.py    From ceph-lcm with Apache License 2.0 5 votes vote down vote up
def mocked_plugin():
    patch = unittest.mock.patch("decapod_common.plugins.get_playbook_plugins")
    with patch as ptch:
        plugin = unittest.mock.MagicMock()

        required_mock = unittest.mock.MagicMock()
        required_mock.pid = 100
        required_mock.returncode = os.EX_OK
        plugin.execute.return_value.__enter__.return_value = required_mock

        ptch.return_value.get.return_value.return_value = plugin

        yield required_mock 
Example #13
Source File: test_process.py    From ceph-lcm with Apache License 2.0 5 votes vote down vote up
def test_command_result(proc):
    proc.options["-c"] = ""
    result = proc.run()

    time.sleep(2)

    assert result.pid
    assert result.returncode == os.EX_OK
    assert result.stdout
    assert result.stdin is None
    assert not result.alive()
    assert str(result)
    assert repr(result) 
Example #14
Source File: gm_app_fw.py    From gmfwtools with Apache License 2.0 5 votes vote down vote up
def main(args):
    if args.offset:
        if args.offset[0:2] == '0x':
            offset = int(args.offset[2:], 16)
        else:
            offset = int(args.offset)
    else:
        offset = 0
    fw = GMAppFirmware(args.fn, offset=offset, verbose=args.debug,
                       fw_version=args.fw_version)
    if args.verify:
        is_ok = fw.do_verify()
        sys.exit(os.EX_OK if is_ok else os.EX_DATAERR)
    elif args.unpack:
        fw.do_unpack(args.out_fn, args.exec_fn)
    elif args.mount:
        if args.target:
            fw.do_mount(mpoint=args.target)
        else:
            fw.do_mount()
    elif args.pack:
        fw.do_pack(args.jffs_image, args.exec_fn)
    elif args.key:
        fw.do_key(args.key, False)
    elif args.keybrute:
        fw.do_key(None, True)
    else:
        print("Usage: one of -v, -u or -p options should be specified")
        sys.exit(os.EX_USAGE) 
Example #15
Source File: ceph_version.py    From ceph-lcm with Apache License 2.0 5 votes vote down vote up
def get_ceph_version(prefix, connection, cluster_name):
    command = "sudo -EHn -- ceph --cluster {0} version".format(
        shlex.quote(cluster_name))
    result = await connection.run(command)

    if result.exit_status != os.EX_OK:
        click.echo(
            "{0}ceph-version (failed {1}): {2}".format(
                prefix, result.exit_status, result.stderr.strip()))
    else:
        click.echo(
            "{0}ceph-version (ok): {1}".format(
                prefix, result.stdout.strip())) 
Example #16
Source File: ceph_verify.py    From ceph-lcm with Apache License 2.0 5 votes vote down vote up
def catch_errors(func):
    @functools.wraps(func)
    def decorator(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as exc:
            LOG.error("Version verification has been failed: %s", exc)
            return os.EX_SOFTWARE

        return os.EX_OK

    return decorator 
Example #17
Source File: taskpool.py    From ceph-lcm with Apache License 2.0 5 votes vote down vote up
def execute(self, tsk, stop_ev):
        # Small hack to prevent execution of callback BEFORE task
        # happen to arrive into self.data. It is possible because
        # submitting task into pool is eager.
        while tsk.id not in self.data:
            time.sleep(0.1)

        plugin = self.get_plugin(tsk)

        with plugin.execute(tsk) as process:
            tsk = tsk.set_executor_data(platform.node(), process.pid)

            LOG.info(
                "Management process for task %s was started. Pid %d",
                tsk, process.pid
            )

            while not stop_ev.is_set() and process.alive():
                stop_ev.wait(0.5)

            process.stop()

            LOG.info(
                "Management process for task %s with PID %d has "
                "stopped with exit code %d",
                tsk, process.pid, process.returncode
             )

            if process.returncode != os.EX_OK:
                raise ChildProcessError(
                    "Process exit with code {0}".format(process.returncode)) 
Example #18
Source File: typecheck.py    From temci with GNU General Public License v3.0 5 votes vote down vote up
def _instancecheck_impl(self, value, info: Info) -> InfoMsg:
        if not isinstance(value, str):
            return info.errormsg(self, value)
        is_valid = True
        if os.path.exists(value):
            if os.path.isdir(value) and os.access(os.path.abspath(value), os.W_OK)\
                    and (self.constraint is None or self.constraint(value)):
                return info.wrap(True)
            return info.errormsg(self, value)
        abs_name = os.path.abspath(value)
        dir_name = os.path.dirname(abs_name)
        if os.path.exists(dir_name) and os.access(dir_name, os.EX_OK) and os.access(dir_name, os.W_OK) \
            and (self.constraint is None or self.constraint(value)):
            return info.wrap(True)
        return info.errormsg(self, value) 
Example #19
Source File: test.py    From yq with Apache License 2.0 5 votes vote down vote up
def run_yq(self, input_data, args, expect_exit_codes={os.EX_OK}, input_format="yaml"):
        stdin, stdout = sys.stdin, sys.stdout
        try:
            sys.stdin = io.StringIO(input_data)
            sys.stdout = io.BytesIO() if USING_PYTHON2 else io.StringIO()
            cli(args, input_format=input_format)
        except SystemExit as e:
            self.assertIn(e.code, expect_exit_codes)
        finally:
            result = sys.stdout.getvalue()
            if USING_PYTHON2:
                result = result.decode("utf-8")
            sys.stdin, sys.stdout = stdin, stdout
        return result 
Example #20
Source File: scheduler_job.py    From airflow with Apache License 2.0 5 votes vote down vote up
def _exit_gracefully(self, signum, frame):  # pylint: disable=unused-argument
        """
        Helper method to clean up processor_agent to avoid leaving orphan processes.
        """
        self.log.info("Exiting gracefully upon receiving signal %s", signum)
        if self.processor_agent:
            self.processor_agent.end()
        sys.exit(os.EX_OK) 
Example #21
Source File: dag_processing.py    From airflow with Apache License 2.0 5 votes vote down vote up
def _exit_gracefully(self, signum, frame):  # pylint: disable=unused-argument
        """
        Helper method to clean up DAG file processors to avoid leaving orphan processes.
        """
        self.log.info("Exiting gracefully upon receiving signal %s", signum)
        self.terminate()
        self.end()
        self.log.debug("Finished terminating DAG processors.")
        sys.exit(os.EX_OK) 
Example #22
Source File: manager.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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.strip().split('\n') 
Example #23
Source File: test.py    From aegea with Apache License 2.0 5 votes vote down vote up
def test_secrets(self):
        unauthorized_ok = [dict(return_codes=[os.EX_OK]),
                           dict(return_codes=[1, os.EX_SOFTWARE], stderr="(AccessDenied|NoSuchKey)")]
        secret_name = "test_secret_{}".format(int(time.time()))
        self.call("{s}=test aegea secrets put {s} --iam-role aegea.launch".format(s=secret_name),
                  shell=True, expect=unauthorized_ok)
        self.call("aegea secrets put {s} --generate-ssh-key --iam-role aegea.launch".format(s=secret_name),
                  shell=True, expect=unauthorized_ok)
        self.call("aegea secrets ls", shell=True, expect=unauthorized_ok)
        self.call("aegea secrets ls --json", shell=True, expect=unauthorized_ok)
        self.call("aegea secrets get {s} --iam-role aegea.launch".format(s=secret_name), shell=True,
                  expect=unauthorized_ok)
        self.call("aegea secrets delete {s} --iam-role aegea.launch".format(s=secret_name), shell=True,
                  expect=unauthorized_ok) 
Example #24
Source File: printing.py    From aegea with Apache License 2.0 5 votes vote down vote up
def page_output(content, pager=None, file=None):
    if file is None:
        file = sys.stdout
    if not content.endswith("\n"):
        content += "\n"

    pager_process = None
    try:
        if file != sys.stdout or not file.isatty() or not content.startswith(border("┌")):
            raise AegeaException()
        content_lines = content.splitlines()
        content_rows = len(content_lines)

        tty_cols, tty_rows = get_terminal_size()

        naive_content_cols = max(len(i) for i in content_lines)
        if tty_rows > content_rows and tty_cols > naive_content_cols:
            raise AegeaException()

        content_cols = max(len(strip_ansi_codes(i)) for i in content_lines)
        if tty_rows > content_rows and tty_cols > content_cols:
            raise AegeaException()

        pager_process = subprocess.Popen(pager or os.environ.get("PAGER", "less -RS"), shell=True,
                                         stdin=subprocess.PIPE, stdout=file)
        pager_process.stdin.write(content.encode("utf-8"))
        pager_process.stdin.close()
        pager_process.wait()
        if pager_process.returncode != os.EX_OK:
            raise AegeaException()
    except Exception as e:
        if not (isinstance(e, IOError) and e.errno == errno.EPIPE):
            file.write(content.encode("utf-8") if USING_PYTHON2 else content)
    finally:
        try:
            pager_process.terminate()
        except BaseException:
            pass 
Example #25
Source File: ssh.py    From aegea with Apache License 2.0 5 votes vote down vote up
def check_output(self, command, input_data=None, stderr=sys.stderr):
        logger.debug('Running "%s"', command)
        ssh_stdin, ssh_stdout, ssh_stderr = self.exec_command(command)
        if input_data is not None:
            ssh_stdin.write(input_data)
        exit_code = ssh_stdout.channel.recv_exit_status()
        stderr.write(ssh_stderr.read().decode("utf-8"))
        if exit_code != os.EX_OK:
            raise Exception('Error while running "{}": {}'.format(command, errno.errorcode.get(exit_code)))
        return ssh_stdout.read().decode("utf-8") 
Example #26
Source File: logs.py    From aegea with Apache License 2.0 5 votes vote down vote up
def grep(args):
    if args.context:
        args.before_context = args.after_context = args.context
    if not args.end_time:
        args.end_time = Timestamp("-0s")
    query = clients.logs.start_query(logGroupName=args.log_group,
                                     startTime=int(timestamp(args.start_time) * 1000),
                                     endTime=int(timestamp(args.end_time) * 1000),
                                     queryString=args.query)
    seen_results = {}
    print_with_context = partial(print_log_event_with_context, before=args.before_context, after=args.after_context)
    try:
        with ThreadPoolExecutor() as executor:
            while True:
                res = clients.logs.get_query_results(queryId=query["queryId"])
                log_record_pointers = []
                for record in res["results"]:
                    event = {r["field"]: r["value"] for r in record}
                    event_hash = hashlib.sha256(json.dumps(event, sort_keys=True).encode()).hexdigest()[:32]
                    if event_hash in seen_results:
                        continue
                    if "@ptr" in event and (args.before_context or args.after_context):
                        log_record_pointers.append(event["@ptr"])
                    else:
                        print_log_event(event)
                    seen_results[event_hash] = event
                if log_record_pointers:
                    executor.map(print_with_context, log_record_pointers)
                if res["status"] == "Complete":
                    break
                elif res["status"] in {"Failed", "Cancelled"}:
                    raise AegeaException("Query status: {}".format(res["status"]))
                time.sleep(1)
    finally:
        try:
            clients.logs.stop_query(queryId=query["queryId"])
        except clients.logs.exceptions.InvalidParameterException:
            pass
    logger.debug("Query %s: %s", query["queryId"], res["statistics"])
    return SystemExit(os.EX_OK if seen_results else os.EX_DATAERR) 
Example #27
Source File: test_linalg.py    From Computable with MIT License 4 votes vote down vote up
def test_xerbla_override():
    # Check that our xerbla has been successfully linked in. If it is not,
    # the default xerbla routine is called, which prints a message to stdout
    # and may, or may not, abort the process depending on the LAPACK package.
    from nose import SkipTest

    try:
        pid = os.fork()
    except (OSError, AttributeError):
        # fork failed, or not running on POSIX
        raise SkipTest("Not POSIX or fork failed.")

    if pid == 0:
        # child; close i/o file handles
        os.close(1)
        os.close(0)
        # Avoid producing core files.
        import resource
        resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
        # These calls may abort.
        try:
            np.linalg.lapack_lite.xerbla()
        except ValueError:
            pass
        except:
            os._exit(os.EX_CONFIG)

        try:
            a = np.array([[1]])
            np.linalg.lapack_lite.dgetrf(
                1, 1, a.astype(np.double),
                0, # <- invalid value
                a.astype(np.intc), 0)
        except ValueError as e:
            if "DGETRF parameter number 4" in str(e):
                # success
                os._exit(os.EX_OK)

        # Did not abort, but our xerbla was not linked in.
        os._exit(os.EX_CONFIG)
    else:
        # parent
        pid, status = os.wait()
        if os.WEXITSTATUS(status) != os.EX_OK or os.WIFSIGNALED(status):
            raise SkipTest('Numpy xerbla not linked in.') 
Example #28
Source File: manager.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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') 
Example #29
Source File: __main__.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def main():
	parser = argparse.ArgumentParser(prog='KingPhisherServer', description='King Phisher Server', conflict_handler='resolve')
	utilities.argp_add_args(parser)
	startup.argp_add_server(parser)
	arguments = parser.parse_args()

	# basic runtime checks
	if sys.version_info < (3, 4):
		color.print_error('the python version is too old (minimum required is 3.4)')
		return 0

	console_log_handler = utilities.configure_stream_logger(arguments.logger, arguments.loglvl)
	del parser

	# configure environment variables and load the config
	find.init_data_path('server')
	if not os.path.exists(arguments.config_file):
		color.print_error('invalid configuration file')
		color.print_error('the specified path does not exist')
		return os.EX_NOINPUT
	if not os.path.isfile(arguments.config_file):
		color.print_error('invalid configuration file')
		color.print_error('the specified path is not a file')
		return os.EX_NOINPUT
	if not os.access(arguments.config_file, os.R_OK):
		color.print_error('invalid configuration file')
		color.print_error('the specified path can not be read')
		return os.EX_NOPERM
	config = configuration.ex_load_config(arguments.config_file)
	if arguments.verify_config:
		color.print_good('configuration verification passed')
		color.print_good('all required settings are present')
		return os.EX_OK
	if config.has_option('server.data_path'):
		find.data_path_append(config.get('server.data_path'))

	if os.getuid():
		color.print_error('the server must be started as root, configure the')
		color.print_error('\'server.setuid_username\' option in the config file to drop privileges')
		return os.EX_NOPERM

	# setup logging based on the configuration
	if config.has_section('logging'):
		log_file = _ex_config_logging(arguments, config, console_log_handler)
	logger.debug("king phisher version: {0} python version: {1}.{2}.{3}".format(version.version, sys.version_info[0], sys.version_info[1], sys.version_info[2]))

	# initialize the plugin manager
	try:
		plugin_manager = plugins.ServerPluginManager(config)
	except errors.KingPhisherError as error:
		if isinstance(error, errors.KingPhisherPluginError):
			color.print_error("plugin error: {0} ({1})".format(error.plugin_name, error.message))
		else:
			color.print_error(error.message)
		return os.EX_SOFTWARE

	status_code = build_and_run(arguments, config, plugin_manager, log_file)
	plugin_manager.shutdown()
	logging.shutdown()
	return status_code