def env_vars_list(deployment_name, version_name, format_):
    """
    List environment variables.

    \b
    - When deployment_name and version_name are provided: the environment variables will be listed on deployment
    version level.
    - When a deployment name is provided, but not a version name: the environment variables will be listed on
    deployment level.
    - When no deployment_name nor a version name is provided: the environment variables will be listed on project level.
    """

    project_name = get_current_project(error=True)

    if version_name and not deployment_name:
        raise Exception("Missing option <deployment_name>")

    client = init_client()
    if version_name:
        response = client.deployment_version_environment_variables_list(
            project_name=project_name,
            deployment_name=deployment_name,
            version=version_name)
    elif deployment_name:
        response = client.deployment_environment_variables_list(
            project_name=project_name, deployment_name=deployment_name)
    else:
        response = client.project_environment_variables_list(
            project_name=project_name)
    client.api_client.close()

    print_list(response, LIST_ITEMS, sorting_col=1, fmt=format_)
示例#2
0
def deployments_upload(deployment_name, version_name, zip_path, overwrite, quiet):
    """
    Upload ZIP to a version of a deployment.

    Please, specify the deployment package `<zip_path>` that should be uploaded.
    Use the `<overwrite>` option to overwrite the deployment package on UbiOps if one already exists for this version.
    """

    project_name = get_current_project(error=True)

    client = init_client()
    current_version = client.deployment_versions_get(
        project_name=project_name, deployment_name=deployment_name, version=version_name
    )

    if overwrite or current_version.status == STATUS_UNAVAILABLE:
        client.revisions_file_upload(
            project_name=project_name, deployment_name=deployment_name, version=version_name, file=zip_path
        )
        client.api_client.close()

        if not quiet:
            click.echo("Deployment was successfully uploaded")
    else:
        client.api_client.close()
        raise Exception("A deployment package already exists for this deployment version")
示例#3
0
def deployments_download(deployment_name, version_name, output_path, quiet):
    """
    Get the version of a deployment.

    The `<output_path>` option will be used as output location of the zip file. If not specified,
    the current directory will be used. If the `<output_path>` is a directory, the zip will be
    saved in `[deployment_name]_[deployment_version]_[datetime.now()].zip`.
    """

    project_name = get_current_project(error=True)

    client = init_client()
    version = client.deployment_versions_get(
        project_name=project_name, deployment_name=deployment_name, version=version_name
    )
    if not version.active_revision:
        raise Exception("No active revision available for this deployment")

    with client.revisions_file_download(project_name=project_name, deployment_name=deployment_name,
                                        version=version_name, revision_id=version.active_revision) as response:
        filename = default_version_zip_name(deployment_name, version_name)
        output_path = write_blob(response.read(), output_path, filename)
    client.api_client.close()

    if not quiet:
        click.echo("Zip stored in: %s" % output_path)
示例#4
0
def exports_get(export_id, output_path, quiet, format_):
    """
    Get the details of an export.

    If you specify the `<output_path>` option, this location will be used to store the
    export details in a yaml file. You can either specify the `<output_path>` as file or
    directory. If the specified `<output_path>` is a directory, the settings will be
    stored in `export.yaml`.
    """

    project_name = get_current_project(error=True)

    client = init_client()
    export = client.exports_get(project_name=project_name, export_id=export_id)
    client.api_client.close()

    if output_path is not None:
        dictionary = format_yaml(
            item=export,
            required_front=['id', 'deployments', 'pipelines', 'environment_variables'],
            as_str=False
        )
        yaml_file = write_yaml(output_path, dictionary, default_file_name="export.yaml")
        if not quiet:
            click.echo('Export details are stored in: %s' % yaml_file)
    else:
        print_item(item=export, row_attrs=GET_ITEMS, fmt=format_)
示例#5
0
def deprecated_batch_requests_create(deployment_name, version_name, data, timeout, format_):
    """
    [DEPRECATED] Create a deployment batch request and retrieve request IDs to collect the results later.
    Deployment requests are only stored for deployment versions with `request_retention_mode` 'full' or 'metadata'.

    Use the option `timeout` to specify the timeout of the request. The minimum value is 10 seconds. The maximum value
    is 345600 (96 hours). The default value is 14400 (4 hours).

    Use the version option to make a batch request to a specific deployment version:
    `ubiops deployments batch_requests create <my-deployment> -v <my-version> --data <input>`

    If not specified, a batch request is made to the default version:
    `ubiops deployments batch_requests create <my-deployment> --data <input>`

    Multiple data inputs can be specified at ones by using the '--data' options multiple times:
    `ubiops deployments batch_requests create <my-deployment> --data <input-1> --data <input-2> --data <input-3>`

    For structured input, specify each data input as JSON formatted string. For example:
    `ubiops deployments batch_requests create <my-deployment> --data "{\\"param1\\": 1, \\"param2\\": \\"two\\"}"`
    """

    if format_ != 'json':
        click.secho(
            "Deprecation warning: 'batch_requests create' is deprecated, use 'requests create --batch' instead",
            fg='red'
        )

    data = list(data)

    project_name = get_current_project(error=True)

    client = init_client()
    deployment = client.deployments_get(project_name=project_name, deployment_name=deployment_name)

    if deployment.input_type == STRUCTURED_TYPE:
        input_data = []
        for d in data:
            input_data.append(parse_json(d))
    else:
        input_data = data

    if version_name is not None:
        response = client.batch_deployment_version_requests_create(
            project_name=project_name, deployment_name=deployment_name, version=version_name, data=input_data,
            timeout=timeout
        )
    else:
        response = client.batch_deployment_requests_create(
            project_name=project_name, deployment_name=deployment_name, data=input_data, timeout=timeout
        )
    client.api_client.close()

    if format_ == 'reference':
        click.echo(format_requests_reference(response))
    elif format_ == 'oneline':
        click.echo(format_requests_oneline(response))
    elif format_ == 'json':
        click.echo(format_json(response))
    else:
        click.echo(format_requests_reference(response))
示例#6
0
def requests_get(deployment_name, version_name, request_id, format_):
    """
    Get one or more stored deployment requests.
    Deployment requests are only stored for deployment versions with `request_retention_mode` 'full' or 'metadata'.

    Use the version option to get a request for a specific deployment version.
    If not specified, the request is retrieved for the default version.

    Multiple request ids can be specified at ones by using the '-id' options multiple times:
    `ubiops deployments requests get <my-deployment> -v <my-version> -id <id-1> -id <id-2> -id <id-3>`
    """

    request_ids = list(request_id)

    project_name = get_current_project(error=True)

    client = init_client()
    if version_name is not None:
        response = client.deployment_version_requests_batch_get(
            project_name=project_name, deployment_name=deployment_name, version=version_name, data=request_ids
        )
    else:
        response = client.deployment_requests_batch_get(
            project_name=project_name, deployment_name=deployment_name, data=request_ids
        )
    client.api_client.close()

    if format_ == 'reference':
        click.echo(format_requests_reference(response))
    elif format_ == 'oneline':
        click.echo(format_requests_oneline(response))
    elif format_ == 'json':
        click.echo(format_json(response))
    else:
        click.echo(format_requests_reference(response))
示例#7
0
def audit_list(deployment_name, pipeline_name, format_, **kwargs):
    """List the audit events.

    Use the command options as filters.
    """

    project_name = get_current_project(error=True)
    client = init_client()

    if deployment_name and pipeline_name:
        raise Exception(
            "Please, filter either on deployment or pipeline name, not both")
    elif deployment_name:
        events = client.deployment_audit_events_list(
            project_name=project_name,
            deployment_name=deployment_name,
            **kwargs)
    elif pipeline_name:
        events = client.pipeline_audit_events_list(project_name=project_name,
                                                   pipeline_name=pipeline_name,
                                                   **kwargs)
    else:
        events = client.project_audit_events_list(project_name=project_name,
                                                  **kwargs)
    client.api_client.close()

    print_list(events, ['date', 'action', 'user', 'event'],
               fmt=format_,
               pager=len(events) > 10)
示例#8
0
def deprecated_batch_requests_list(deployment_name, version_name, offset, limit, format_):
    """
    [DEPRECATED] List deployment batch requests.
    Deployment requests are only stored for deployment versions with `request_retention_mode` 'full' or 'metadata'.

    Use the version option to list the batch requests for a specific deployment version.
    If not specified, the batch requests are listed for the default version.
    """

    if format_ != 'json':
        click.secho(
            "Deprecation warning: 'batch_requests list' is deprecated, use 'requests list' instead",
            fg='red'
        )

    project_name = get_current_project(error=True)

    client = init_client()
    if version_name is not None:
        response = client.deployment_version_requests_list(
            project_name=project_name, deployment_name=deployment_name, version=version_name, limit=limit, offset=offset
        )
    else:
        response = client.deployment_requests_list(
            project_name=project_name, deployment_name=deployment_name, limit=limit, offset=offset
        )
    client.api_client.close()

    print_list(response, REQUEST_LIST_ITEMS, fmt=format_)
    if len(response) == limit:
        click.echo("\n(Use the <offset> and <limit> options to load more)")
示例#9
0
def schedules_create(schedule_name, object_type, object_name, object_version,
                     data, format_, **kwargs):
    """
    Create a new request schedule.

    - For express mode deployments, direct requests will be made
    - For batch mode deployments, batch requests will be made
    - For pipelines, batch requests will be made
    """

    project_name = get_current_project(error=True)

    client = init_client()
    obj = get_schedule_object(client, project_name, object_type, object_name)

    if obj.input_type == STRUCTURED_TYPE:
        data = parse_json(data)

    schedule = api.ScheduleCreate(name=schedule_name,
                                  object_type=object_type,
                                  object_name=object_name,
                                  version=object_version,
                                  request_data=data,
                                  **kwargs)
    response = client.request_schedules_create(project_name=project_name,
                                               data=schedule)
    client.api_client.close()

    print_item(response, LIST_ITEMS, rename=RENAME_COLUMNS, fmt=format_)
示例#10
0
def schedules_update(schedule_name, new_name, data, format_, **kwargs):
    """Update a request schedule."""

    project_name = get_current_project(error=True)

    client = init_client()

    if data is not None:
        schedule = client.request_schedules_get(project_name=project_name,
                                                schedule_name=schedule_name)
        obj = get_schedule_object(client, project_name, schedule.object_type,
                                  schedule.object_name)
        if obj.input_type == STRUCTURED_TYPE:
            data = parse_json(data)

    new_schedule = api.ScheduleUpdate(
        name=new_name,
        request_data=data,
        **{k: v
           for k, v in kwargs.items() if v is not None})
    response = client.request_schedules_update(project_name=project_name,
                                               schedule_name=schedule_name,
                                               data=new_schedule)
    client.api_client.close()

    print_item(response, LIST_ITEMS, rename=RENAME_COLUMNS, fmt=format_)
def pipeline_versions_list(pipeline_name, labels, format_):
    """
    List the versions of a pipeline.

    The `<labels>` option can be used to filter on specific labels.
    """

    label_filter = get_label_filter(labels)

    project_name = get_current_project(error=True)

    client = init_client()
    default = client.pipelines_get(project_name=project_name,
                                   pipeline_name=pipeline_name).default_version
    response = client.pipeline_versions_list(project_name=project_name,
                                             pipeline_name=pipeline_name,
                                             labels=label_filter)
    client.api_client.close()

    if format_ == 'table':
        # Add [DEFAULT] to default version
        for i in response:
            if default and hasattr(i, 'version') and i.version == default:
                i.version = f"{i.version} {click.style('[DEFAULT]', fg='yellow')}"

    print_list(items=response,
               attrs=LIST_ITEMS,
               rename_cols={
                   'version': 'version_name',
                   **PIPELINE_VERSION_FIELDS_RENAMED
               },
               sorting_col=0,
               fmt=format_)
示例#12
0
def deprecated_pipelines_request(pipeline_name, version_name, data,
                                 pipeline_timeout, deployment_timeout,
                                 format_):
    """
    [DEPRECATED] Create a pipeline request and retrieve the result.

    Use the version option to make a request to a specific pipeline version:
    `ubiops pipelines request <my-deployment> -v <my-version> --data <input>`

    If not specified, a request is made to the default version:
    `ubiops pipelines request <my-deployment> --data <input>`

    For structured input, specify the data as JSON formatted string. For example:
    `ubiops pipelines request <my-deployment> --data "{\\"param1\\": 1, \\"param2\\": \\"two\\"}"`
    """

    if format_ != 'json':
        click.secho(
            "Deprecation warning: 'request' is deprecated, use 'requests create' instead",
            fg='red')

    project_name = get_current_project(error=True)

    client = init_client()
    pipeline = client.pipelines_get(project_name=project_name,
                                    pipeline_name=pipeline_name)

    if pipeline.input_type == STRUCTURED_TYPE:
        data = parse_json(data)

    if version_name is not None:
        response = client.pipeline_version_requests_create(
            project_name=project_name,
            pipeline_name=pipeline_name,
            version=version_name,
            data=data,
            pipeline_timeout=pipeline_timeout,
            deployment_timeout=deployment_timeout)

    else:
        response = client.pipeline_requests_create(
            project_name=project_name,
            pipeline_name=pipeline_name,
            data=data,
            pipeline_timeout=pipeline_timeout,
            deployment_timeout=deployment_timeout)

    client.api_client.close()
    if format_ == 'reference':
        click.echo(format_pipeline_requests_reference([response]))

    elif format_ == 'oneline':
        click.echo(format_pipeline_requests_oneline([response]))

    elif format_ == 'json':
        click.echo(format_json(response))

    else:
        click.echo(format_pipeline_requests_reference([response]))
def env_vars_create(env_var_name, env_var_value, secret, deployment_name,
                    version_name, yaml_file, format_):
    """
    Create an environment variable.

    \b
    - When deployment_name and version_name are provided: the environment variable will be created on deployment
    version level.
    - When a deployment name is provided, but not a version name: the environment variable will be created on
    deployment level.
    - When no deployment_name nor a version name is provided: the environment variable will be created on project level.

    \b
    It is possible to create multiple environment variables at ones by passing a yaml file.
    The structure of this file is assumed to look like:
    ```
    environment_variables:
      - name: env_var_1
        value: value_1
      - name: env_var_2
        value: value_2
        secret: true
      - name: env_var_3
        value: value_3
        secret: true
    ```
    The 'secret' parameter is optional, and is `false` by default.
    """

    project_name = get_current_project(error=True)

    if not yaml_file and not env_var_name:
        raise Exception(
            "Please, specify the environment variable in either a yaml file or as a command argument"
        )
    if yaml_file and (env_var_name or env_var_value or secret):
        raise Exception(
            "Please, use either a yaml file or command options, not both")
    if version_name and not deployment_name:
        raise Exception("Missing option <deployment_name>")

    if yaml_file:
        yaml_content = read_yaml(yaml_file,
                                 required_fields=['environment_variables'])
        check_required_fields(input_dict=yaml_content,
                              list_name='environment_variables',
                              required_fields=['name', 'value'])

        items = []
        for env_var in yaml_content['environment_variables']:
            secret = env_var['secret'] if 'secret' in env_var else False
            item = create_env_var(project_name, deployment_name, version_name,
                                  env_var['name'], env_var['value'], secret)
            items.append(item)
        print_list(items, LIST_ITEMS, fmt=format_)
    else:
        item = create_env_var(project_name, deployment_name, version_name,
                              env_var_name, env_var_value, secret)
        print_item(item, LIST_ITEMS, fmt=format_)
示例#14
0
def signin(type_, api_endpoint, email, password):
    """Sign in using your credentials.

    If you want to use a service token, use the `<token>` flag option."""

    assert len(api_endpoint) > 0, 'Please, specify the UbiOps API endpoint'
    # API endpoint should not end with a '/'
    api_endpoint = api_endpoint[:-1] if api_endpoint[
        -1] == "/" else api_endpoint

    if type_ == 'bearer':
        if not email:
            email = click.prompt('Email', default=Config().get("auth.email"))

        provider, url = sign_in(api_endpoint=api_endpoint, email=email)

        if provider == 'ubiops':
            if not password:
                password = click.prompt('Password', hide_input=True)
            success = authorize(api_endpoint, email, password)
            if not success:
                token2fa = click.prompt('Two factor authentication token',
                                        hide_input=True)
                authorize2fa(api_endpoint, email, password, token2fa)

        else:
            raise NotImplementedError(
                "Sign-in type %s not supported in the CLI.\n"
                "Please, use an API Token to sign in. You can create one in the WebApp "
                "in the Users & Permissions panel." % provider)

    elif type_ == 'token':
        if not password:
            password = click.prompt('API Token', hide_input=True)
        if not password.startswith('Token '):
            click.echo(
                "%s Token should be formatted like`\"Token 1abc2def3ghi4jkl5mno6pqr7stu8vwx9yz\"`"
                % click.style('Warning:', fg='yellow'))

        try:
            raise_for_status(api_endpoint=api_endpoint, token=password)
        except Exception:
            raise Exception('Could not authorize')

    click.echo("\nWelcome to UbiOps!")

    project = get_current_project(check_existing=True)
    if project:
        click.echo("\nSelected project: %s" %
                   click.style(project, fg='yellow'))
        click.echo(
            "To change the selected project, use: `ubiops current_project set <PROJECT_NAME>`"
        )
    else:
        click.echo("\n%s" % click.style("No projects found", fg='yellow'))
        click.echo(
            "To create a project, use: `ubiops projects create <PROJECT_NAME>`"
        )
示例#15
0
def pipelines_create(pipeline_name, yaml_file, format_):
    """
    Create a new pipeline.

    \b
    Define the pipeline parameters using a yaml file.
    For example:
    ```
    pipeline_name: my-pipeline-name
    pipeline_description: Pipeline created via command line.
    pipeline_labels:
      my-key-1: my-label-1
      my-key-2: my-label-2
    input_type: structured
    input_fields:
      - name: my-pipeline-param1
        data_type: int
    output_type: structured
    output_fields:
      - name: my-pipeline-output1
        data_type: int
    ```

    Possible input/output types: [structured, plain].
    Possible data_types: [blob, int, string, double, bool, array_string, array_int, array_double].
    """

    client = init_client()
    project_name = get_current_project(error=True)

    yaml_content = read_yaml(yaml_file,
                             required_fields=PIPELINE_REQUIRED_FIELDS)
    assert 'pipeline_name' in yaml_content or pipeline_name, \
        'Please, specify the pipeline name in either the yaml file or as a command argument'

    pipeline_fields, input_fields, output_fields = define_pipeline(
        yaml_content, pipeline_name)
    pipeline_data = api.PipelineCreate(**pipeline_fields, **input_fields,
                                       **output_fields)
    pipeline_response = client.pipelines_create(project_name=project_name,
                                                data=pipeline_data)
    client.api_client.close()

    print_item(pipeline_response,
               row_attrs=LIST_ITEMS,
               required_front=['name', 'description', 'input_type'],
               optional=[
                   'input_fields name', 'input_fields data_type',
                   'output_type', 'output_fields name',
                   'output_fields data_type', 'creation_date', 'last_updated'
               ],
               rename={
                   'name': 'pipeline_name',
                   'description': 'pipeline_description'
               },
               fmt=format_)
示例#16
0
def current_project_get(format_):
    """Get your current CLI project."""

    current = get_current_project()

    client = init_client()
    response = client.projects_get(project_name=current)
    client.api_client.close()

    print_projects_list([response], current, LIST_ITEMS, fmt=format_)
示例#17
0
def deployments_update(deployment_name, new_name, default_version, yaml_file, quiet):
    """
    Update a deployment.

    If you only want to update the name of the deployment or the default deployment version,
    use the options `<new_name>` and `<default_version>`.
    If you want to update the deployment input/output fields, description or labels, please use a yaml file to define
    the new deployment.

    \b
    For example:
    ```
    deployment_description: Deployment created via command line.
    deployment_labels:
      my-key-1: my-label-1
      my-key-2: my-label-2
    input_fields:
      - name: param1
        data_type: int
      - name: param2
        data_type: string
    output_fields:
      - name: param1
        data_type: int
      - name: param2
        data_type: string
    ```
    """

    project_name = get_current_project(error=True)

    yaml_content = read_yaml(yaml_file)

    deployment = api.DeploymentUpdate(name=new_name, default_version=default_version)
    if 'deployment_description' in yaml_content:
        deployment.description = yaml_content['deployment_description']
    if 'deployment_labels' in yaml_content:
        deployment.labels = yaml_content['deployment_labels']
    if 'input_fields' in yaml_content and isinstance(yaml_content['input_fields'], list):
        deployment.input_fields = [
            api.DeploymentInputFieldCreate(name=item['name'], data_type=item['data_type'])
            for item in yaml_content['input_fields']
        ]
    if 'output_fields' in yaml_content and isinstance(yaml_content['output_fields'], list):
        deployment.output_fields = [
            api.DeploymentInputFieldCreate(name=item['name'], data_type=item['data_type'])
            for item in yaml_content['output_fields']
        ]

    client = init_client()
    client.deployments_update(project_name=project_name, deployment_name=deployment_name, data=deployment)
    client.api_client.close()

    if not quiet:
        click.echo("Deployment was successfully updated")
def revisions_list(deployment_name, version_name, format_):
    """
    List the revisions of a deployment version.
    """

    project_name = get_current_project(error=True)

    client = init_client()
    response = client.revisions_list(project_name=project_name, deployment_name=deployment_name, version=version_name)
    client.api_client.close()

    print_list(response, LIST_ITEMS, sorting_col=0, fmt=format_)
示例#19
0
def pipelines_get(pipeline_name, output_path, quiet, format_):
    """
    Get the pipeline settings, like, input_type and input_fields.

    If you specify the <output_path> option, this location will be used to store the
    pipeline structure in a yaml file. You can either specify the <output_path> as file or
    directory. If the specified <output_path> is a directory, the settings will be
    stored in `pipeline.yaml`.
    """

    project_name = get_current_project(error=True)

    client = init_client()
    pipeline = client.pipelines_get(project_name=project_name,
                                    pipeline_name=pipeline_name)
    client.api_client.close()

    if output_path is not None:
        dictionary = format_yaml(
            pipeline,
            required_front=['name', 'description', 'input_type'],
            optional=[
                'input_fields name', 'input_fields data_type', 'output_type',
                'output_fields name', 'output_fields data_type'
            ],
            rename={
                'name': 'pipeline_name',
                'description': 'pipeline_description'
            },
            as_str=False)

        yaml_file = write_yaml(output_path,
                               dictionary,
                               default_file_name="pipeline.yaml")
        if not quiet:
            click.echo('Pipeline file is stored in: %s' % yaml_file)

    else:
        print_item(pipeline,
                   row_attrs=LIST_ITEMS,
                   required_front=['name', 'description', 'input_type'],
                   optional=[
                       'input_fields name', 'input_fields data_type',
                       'output_type', 'output_fields name',
                       'output_fields data_type', 'creation_date',
                       'last_updated', 'default_version'
                   ],
                   rename={
                       'name': 'pipeline_name',
                       'description': 'pipeline_description'
                   },
                   fmt=format_)
def builds_get(deployment_name, version_name, build_id, format_):
    """Get the build of a deployment version."""

    project_name = get_current_project(error=True)

    client = init_client()
    build = client.builds_get(project_name=project_name,
                              deployment_name=deployment_name,
                              version=version_name,
                              build_id=build_id)
    client.api_client.close()

    print_item(build, row_attrs=LIST_ITEMS, fmt=format_)
示例#21
0
def exports_list(status, format_):
    """
    List all your exports in your project.

    The `<status>` option can be used to filter on specific statuses.
    """

    project_name = get_current_project()
    if project_name:
        client = init_client()
        exports = client.exports_list(project_name=project_name, status=status)
        client.api_client.close()
        print_list(items=exports, attrs=LIST_ITEMS, sorting_col=1, sorting_reverse=True, fmt=format_)
def revisions_upload(deployment_name, version_name, zip_path, format_):
    """Create a revision of a deployment version by uploading a ZIP.

    Please, specify the deployment package `<zip_path>` that should be uploaded.
    """

    project_name = get_current_project(error=True)

    client = init_client()
    revision = client.revisions_file_upload(project_name=project_name, deployment_name=deployment_name,
                                            version=version_name, file=zip_path)
    client.api_client.close()

    print_item(revision, row_attrs=['revision', 'build'], fmt=format_)
示例#23
0
def schedules_list(format_):
    """List request schedules in project."""

    project_name = get_current_project(error=True)

    client = init_client()
    response = client.request_schedules_list(project_name=project_name)
    client.api_client.close()

    print_list(response,
               LIST_ITEMS,
               rename_cols=RENAME_COLUMNS,
               sorting_col=1,
               fmt=format_)
示例#24
0
def schedules_get(schedule_name, format_):
    """Get a request schedule."""

    project_name = get_current_project(error=True)

    client = init_client()
    response = client.request_schedules_get(project_name=project_name,
                                            schedule_name=schedule_name)
    client.api_client.close()

    print_item(response,
               row_attrs=LIST_ITEMS,
               rename=RENAME_COLUMNS,
               fmt=format_)
示例#25
0
def blobs_list(format_):
    """List blobs in project."""

    project_name = get_current_project(error=True)

    client = init_client()
    response = client.blobs_list(project_name=project_name)
    client.api_client.close()

    print_list(response,
               LIST_ITEMS,
               rename_cols={'ttl': 'time_to_live'},
               sorting_col=2,
               fmt=format_)
示例#26
0
def blobs_get(blob_id, output_path, quiet):
    """Download an existing blob."""

    project_name = get_current_project(error=True)

    client = init_client()
    with client.blobs_get(project_name=project_name,
                          blob_id=blob_id) as response:
        filename = response.getfilename()
        output_path = write_blob(response.read(), output_path, filename)
    client.api_client.close()

    if not quiet:
        click.echo("Blob stored in: %s" % output_path)
示例#27
0
def blobs_delete(blob_id, assume_yes, quiet):
    """Delete a blob."""

    project_name = get_current_project(error=True)

    if assume_yes or click.confirm("Are you sure you want to delete blob <%s> "
                                   "of project <%s>?" %
                                   (blob_id, project_name)):
        client = init_client()
        client.blobs_delete(project_name=project_name, blob_id=blob_id)
        client.api_client.close()

        if not quiet:
            click.echo("Blob was successfully deleted")
示例#28
0
def deprecated_batch_requests_get(pipeline_name, version_name, request_id,
                                  format_):
    """
    [DEPRECATED] Get the results of one or more pipeline batch requests.
    Pipeline requests are only stored for pipeline versions with `request_retention_mode` 'full' or 'metadata'.

    Use the version option to get a batch request for a specific pipeline version.
    If not specified, the batch request is retrieved for the default version.

    Multiple request ids can be specified at ones by using the '-id' options multiple times:
    `ubiops pipelines batch_requests get <my-pipeline> -v <my-version> -id <id-1> -id <id-2> -id <id-3>`
    """

    if format_ != 'json':
        click.secho(
            "Deprecation warning: 'batch_requests get' is deprecated, use 'requests get' instead",
            fg='red')

    request_ids = list(request_id)

    project_name = get_current_project(error=True)

    client = init_client()
    if version_name is not None:
        response = client.pipeline_version_requests_batch_get(
            project_name=project_name,
            pipeline_name=pipeline_name,
            version=version_name,
            data=request_ids)

    else:
        response = client.pipeline_requests_batch_get(
            project_name=project_name,
            pipeline_name=pipeline_name,
            data=request_ids)

    client.api_client.close()

    if format_ == 'reference':
        click.echo(format_pipeline_requests_reference(response))

    elif format_ == 'oneline':
        click.echo(format_pipeline_requests_oneline(response))

    elif format_ == 'json':
        click.echo(format_json(response))

    else:
        click.echo(format_pipeline_requests_reference(response))
示例#29
0
def requests_list(pipeline_name, version_name, limit, format_, **kwargs):
    """
    List pipeline requests.
    Pipeline requests are only stored for pipeline versions with `request_retention_mode` 'full' or 'metadata'.

    Use the version option to list the requests for a specific pipeline version.
    If not specified, the requests are listed for the default version.
    """

    project_name = get_current_project(error=True)

    if 'start_date' in kwargs and kwargs['start_date']:
        try:
            kwargs['start_date'] = format_datetime(parse_datetime(
                kwargs['start_date']),
                                                   fmt='%Y-%m-%dT%H:%M:%SZ')
        except ValueError:
            raise Exception(
                "Failed to parse start_date. Please use iso-format, "
                "for example, '2020-01-01T00:00:00.000000Z'")

    if 'end_date' in kwargs and kwargs['end_date']:
        try:
            kwargs['end_date'] = format_datetime(parse_datetime(
                kwargs['end_date']),
                                                 fmt='%Y-%m-%dT%H:%M:%SZ')
        except ValueError:
            raise Exception("Failed to parse end_date. Please use iso-format, "
                            "for example, '2020-01-01T00:00:00.000000Z'")

    client = init_client()
    if version_name is not None:
        response = client.pipeline_version_requests_list(
            project_name=project_name,
            pipeline_name=pipeline_name,
            version=version_name,
            limit=limit,
            **kwargs)

    else:
        response = client.pipeline_requests_list(project_name=project_name,
                                                 pipeline_name=pipeline_name,
                                                 limit=limit,
                                                 **kwargs)

    client.api_client.close()
    print_list(response, REQUEST_LIST_ITEMS, fmt=format_)
    if len(response) == limit:
        click.echo("\n(Use the <offset> and <limit> options to load more)")
def revisions_get(deployment_name, version_name, revision_id, format_):
    """Get a revision of a deployment version."""

    project_name = get_current_project(error=True)

    client = init_client()
    revision = client.revisions_get(
        project_name=project_name,
        deployment_name=deployment_name,
        version=version_name,
        revision_id=revision_id
    )
    client.api_client.close()

    print_item(revision, row_attrs=LIST_ITEMS, fmt=format_)