Пример #1
0
    def run(self):
        hub_url = self.context.get("hub_url")
        token = self.context.get("token")
        org_name = self.context.get("org", {}).get("name")
        workspace_name = self.context.get("workspace", {}).get("name")
        experiment = self.context.get("experiment")

        with TemporaryDirectory() as dname:
            settings_path = os.path.join(dname, "settings.yaml")
            settings = {}
            set_chaos_hub_settings(hub_url, token, settings)
            save_settings(settings, settings_path)

            experiment_path = os.path.join(dname, "experiment.json")
            with open(experiment_path, "w") as f:
                f.write(json.dumps(experiment["payload"]))

            cmd = [
                self.chaostoolkit_cli_path, '--settings', settings_path, 'run',
                '--org', org_name, '--workspace', workspace_name,
                experiment_path
            ]

            self.proc = subprocess.Popen(cmd,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE,
                                         env=os.environ,
                                         cwd=dname)
            self.proc.wait()
Пример #2
0
def team(ctx: click.Context):
    """
    List and select a new ChaosIQ team to use within the default organization.

    \b
    In order to benefit from these features, you must have registered with
    ChaosIQ and retrieved an access token. You should set that
    token in the configuration file with `chaos signin`.
    """
    settings_path = ctx.obj["settings_path"]
    settings = load_settings(settings_path) or {}

    url = get_endpoint_url(settings, "https://console.chaosiq.io")

    token = get_auth_token(settings, url)
    disable_tls_verify = get_verify_tls(settings)

    if not token:
        establish_credentials(settings_path)
    else:
        default_org = get_default_org(settings)
        default_team = select_team(url, token, default_org, disable_tls_verify)

        set_settings(url, token, disable_tls_verify, default_org, default_team,
                     settings)
        save_settings(settings, settings_path)

        click.echo("ChaosIQ details saved at {}".format(settings_path))
Пример #3
0
def disable(ctx: click.Context, feature: str):
    """
    Disable one of the extension's features: `publish` which pushes experiment
    and executions to ChaosIQ. `safeguards` which validates the
    run is allowed to continue at runtime.
    """
    settings_path = ctx.obj["settings_path"]
    settings = load_settings(settings_path)
    disable_feature(settings, feature)
    save_settings(settings, settings_path)
Пример #4
0
def test_create_settings_file_on_save():
    ghost = os.path.abspath(os.path.join(settings_dir, "bah", "ghost.yaml"))
    assert not os.path.exists(ghost)
    try:
        save_settings({}, ghost)
        assert os.path.exists(ghost)
    finally:
        try:
            os.remove(ghost)
        except OSError:
            pass
Пример #5
0
def test_save_settings():
    settings = load_settings(os.path.join(settings_dir, "settings.yaml"))
    new_settings_location = os.path.join(settings_dir, "new_settings.yaml")
    try:
        os.remove(new_settings_location)
    except OSError:
        pass
    save_settings(settings, new_settings_location)
    saved_settings = load_settings(new_settings_location)
    assert "notifications" in saved_settings
    os.remove(new_settings_location)
Пример #6
0
def establish_credentials(settings_path):
    settings = load_settings(settings_path) or {}

    default_url = get_endpoint_url(settings, "https://console.chaosiq.io")

    url = click.prompt(click.style("ChaosIQ url", fg='green'),
                       type=str,
                       show_default=True,
                       default=default_url)
    url = urlparse(url)
    url = "://".join([url.scheme, url.netloc])

    token = click.prompt(click.style("ChaosIQ token", fg='green'),
                         type=str,
                         hide_input=True)
    token = token.strip()

    verify_tls = True
    try:
        r = verify_ssl_certificate(url, token)
        if r.status_code == 401:
            click.echo("Your token was not accepted by the server.")
            raise click.Abort()
    except requests.exceptions.SSLError:
        verify_tls = not click.confirm(
            "It looks like the server's TLS certificate cannot be verified. "
            "Do you wish to disable certificate verification for this server?")

    if not verify_tls:  # pragma: no cover
        requests.packages.urllib3.disable_warnings(
            category=InsecureRequestWarning)

    default_org = select_organization(url, token, verify_tls)
    if not default_org:
        click.secho(
            "No default organization selected! Aborting configuration.",
            fg="red")
        return

    default_team = select_team(url, token, default_org, verify_tls)
    if not default_team:
        click.secho("No default team selected! Aborting configuration.",
                    fg="red")
        return

    set_settings(url, token, verify_tls, default_org, default_team, settings)
    save_settings(settings, settings_path)

    click.echo("ChaosIQ details saved at {}".format(settings_path))
Пример #7
0
def test_verify_source_path_must_exist(log_file, default_settings: Dict[str,
                                                                        Any]):
    with NamedTemporaryFile(suffix="yaml") as settings_file:
        save_settings(default_settings, settings_file.name)

        runner = CliRunner()
        result = runner.invoke(cli, [
            '--settings', settings_file.name, '--log-file', log_file.name,
            'verify', 'invalid.jsn'
        ])
        assert result.exit_code == 1
        assert result.exception

        log_file.seek(0)
        log = log_file.read().decode('utf-8')
        assert 'Path "invalid.jsn" does not exist.' in log
def login(ctx: click.Context):
    """
    Login to a Chaos Hub.
    """
    settings_path = ctx.obj["settings_path"]
    settings = load_settings(settings_path)

    hub_url = click.prompt(
        click.style("Chaos Hub Url", fg='green'), type=str, show_default=True,
        default="https://chaoshub.com")

    token = click.prompt(
        click.style("Chaos Hub Token", fg='green'), type=str, hide_input=True)

    set_chaos_hub_settings(hub_url, token, settings)
    save_settings(settings, settings_path)

    click.echo("Chaos Hub details saved at {}".format(
        settings_path))
Пример #9
0
def remove_settings_value(ctx: click.Context, key: str):
    """
    Remove a settings key and its children.

    The key must be dotted path to its location in the settings file.
    """
    if not os.path.isfile(ctx.obj["settings_path"]):
        ctx.exit(1)

    settings = load_settings(ctx.obj["settings_path"]) or {}
    item = locate_settings_entry(settings, key)
    if not item:
        ctx.exit(1)
    parent, entry, key_tail, index = item

    if key_tail is not None:
        parent.pop(key_tail, None)
    elif index is not None:
        parent.remove(parent[index])
    save_settings(settings, ctx.obj["settings_path"])
Пример #10
0
def configure(ctx: click.Context,
              token: str = None,
              default_api_url: str = None):
    settings_path = ctx.obj["settings_path"]
    settings = load_settings(settings_path) or {}

    # set default url for API calls
    api_url = get_api_url(settings)
    if default_api_url:
        api_url = urlparse(default_api_url)
        api_url = \
            "{}://{}{}".format(
                api_url.scheme,
                api_url.netloc,
                api_url.path)
    api_url = api_url or DEFAULT_PROOFDOCK_API_URL

    set_settings(settings, api_url, token)
    save_settings(settings, settings_path)
    click.echo(
        click.style("Configuration saved at {}".format(settings_path),
                    fg='green'))
Пример #11
0
def set_settings_value(ctx: click.Context, key: str, value: str = None):
    """
    Set a settings value.
    The value must be a valid JSON string so that it can be interpreted
    with the appropriate type.

    The key must be dotted path to its location in the settings file.
    """
    if not os.path.isfile(ctx.obj["settings_path"]):
        ctx.exit(1)

    settings = load_settings(ctx.obj["settings_path"]) or {}
    item = locate_settings_entry(settings, key)
    if not item:
        ctx.exit(1)
    parent, entry, key_tail, index = item

    value = json.loads(value)
    if key_tail is not None:
        parent[key_tail] = value
    elif index is not None:
        parent[index] = value
    save_settings(settings, ctx.obj["settings_path"])