def __init__(self, collection_config):

    entity_name = collection_config.entity_name
    name_template = path_template.PathTemplate(collection_config.name_pattern)
    id_segments = [seg.literal for seg in name_template.segments
          if seg.kind == path_template._BINDING]

    self.format_name_upper = casing_utils.get_resource_type_class_name(
        entity_name)
    self.format_name_lower = casing_utils.get_resource_type_var_name(
        entity_name)
    self.type_name_upper = casing_utils.get_resource_type_from_class_name(
        self.format_name_upper)
    self.parameter_list = [
        {
            'parameter': casing_utils.lower_underscore_to_lower_camel(lit),
            'parameter_name': lit,
            'not_first': True,
            'not_last': True,
        } for lit in id_segments]
    self.parameter_list[0]['not_first'] = False
    self.parameter_list[-1]['not_last'] = False
    self.format_fields = [
        {
            'upper': casing_utils.lower_camel_to_upper_camel(f['parameter']),
            'lower': f['parameter'],
        } for f in self.parameter_list]
    self.format_string = collection_config.name_pattern
Exemple #2
0
    def __init__(self, collection_config, java_package, oneof):

        entity_name = collection_config.java_entity_name
        name_template = path_template.PathTemplate(
            collection_config.name_pattern)
        id_segments = [
            seg.literal for seg in name_template.segments
            if seg.kind == path_template._BINDING
        ]

        self.format_name_upper = casing_utils.get_resource_type_class_name(
            entity_name)
        self.format_name_lower = casing_utils.get_resource_type_var_name(
            entity_name)
        self.type_name_upper = casing_utils.get_resource_type_from_class_name(
            self.format_name_upper)
        if oneof:
            self.parent_interface = casing_utils.get_parent_resource_name_class_name(
                oneof.oneof_name)
            self.extension_keyword = 'extends'
        else:
            self.parent_interface = 'ResourceName'
            self.extension_keyword = 'implements'
        self.parameter_list = [{
            'parameter':
            casing_utils.lower_underscore_to_lower_camel(lit),
            'parameter_name':
            lit,
            'not_first':
            True,
            'not_last':
            True,
        } for lit in id_segments]
        self.parameter_list[0]['not_first'] = False
        self.parameter_list[-1]['not_last'] = False
        self.format_fields = [{
            'upper':
            casing_utils.lower_camel_to_upper_camel(f['parameter']),
            'lower':
            f['parameter'],
        } for f in self.parameter_list]
        self.format_string = collection_config.name_pattern
        self.package_name = java_package
class FirestoreAdminClient(object):
    """
    The Cloud Firestore Admin API.

    This API provides several administrative services for Cloud Firestore.

    # Concepts

    Project, Database, Namespace, Collection, and Document are used as defined in
    the Google Cloud Firestore API.

    Operation: An Operation represents work being performed in the background.


    # Services

    ## Index

    The index service manages Cloud Firestore indexes.

    Index creation is performed asynchronously.
    An Operation resource is created for each such asynchronous operation.
    The state of the operation (including any errors encountered)
    may be queried via the Operation resource.

    ## Metadata

    Provides metadata and statistical information about data in Cloud Firestore.
    The data provided as part of this API may be stale.

    ## Operation

    The Operations collection provides a record of actions performed for the
    specified Project (including any Operations in progress). Operations are not
    created directly but through calls on other collections or resources.

    An Operation that is not yet done may be cancelled. The request to cancel is
    asynchronous and the Operation may continue to run for some time after the
    request to cancel is made.

    An Operation that is done may be deleted so that it is no longer listed as
    part of the Operation collection.

    Operations are created by service ``FirestoreAdmin``, but are accessed via
    service ``google.longrunning.Operations``.
    """

    SERVICE_ADDRESS = 'firestore.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _PAGE_DESCRIPTORS = {
        'list_indexes': _PageDesc('page_token', 'next_page_token', 'indexes')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = (
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/datastore', )

    _DATABASE_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/databases/{database}')
    _INDEX_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/databases/{database}/indexes/{index}')

    @classmethod
    def database_path(cls, project, database):
        """Returns a fully-qualified database resource name string."""
        return cls._DATABASE_PATH_TEMPLATE.render({
            'project': project,
            'database': database,
        })

    @classmethod
    def index_path(cls, project, database, index):
        """Returns a fully-qualified index resource name string."""
        return cls._INDEX_PATH_TEMPLATE.render({
            'project': project,
            'database': database,
            'index': index,
        })

    @classmethod
    def match_project_from_database_name(cls, database_name):
        """Parses the project from a database resource.

        Args:
            database_name (str): A fully-qualified path representing a database
                resource.

        Returns:
            A string representing the project.
        """
        return cls._DATABASE_PATH_TEMPLATE.match(database_name).get('project')

    @classmethod
    def match_database_from_database_name(cls, database_name):
        """Parses the database from a database resource.

        Args:
            database_name (str): A fully-qualified path representing a database
                resource.

        Returns:
            A string representing the database.
        """
        return cls._DATABASE_PATH_TEMPLATE.match(database_name).get('database')

    @classmethod
    def match_project_from_index_name(cls, index_name):
        """Parses the project from a index resource.

        Args:
            index_name (str): A fully-qualified path representing a index
                resource.

        Returns:
            A string representing the project.
        """
        return cls._INDEX_PATH_TEMPLATE.match(index_name).get('project')

    @classmethod
    def match_database_from_index_name(cls, index_name):
        """Parses the database from a index resource.

        Args:
            index_name (str): A fully-qualified path representing a index
                resource.

        Returns:
            A string representing the database.
        """
        return cls._INDEX_PATH_TEMPLATE.match(index_name).get('database')

    @classmethod
    def match_index_from_index_name(cls, index_name):
        """Parses the index from a index resource.

        Args:
            index_name (str): A fully-qualified path representing a index
                resource.

        Returns:
            A string representing the index.
        """
        return cls._INDEX_PATH_TEMPLATE.match(index_name).get('index')

    def __init__(self,
                 channel=None,
                 credentials=None,
                 ssl_credentials=None,
                 scopes=None,
                 client_config=None,
                 lib_name=None,
                 lib_version='',
                 metrics_headers=()):
        """Constructor.

        Args:
            channel (~grpc.Channel): A ``Channel`` instance through
                which to make calls.
            credentials (~google.auth.credentials.Credentials): The authorization
                credentials to attach to requests. These credentials identify this
                application to the service.
            ssl_credentials (~grpc.ChannelCredentials): A
                ``ChannelCredentials`` instance for use with an SSL-enabled
                channel.
            scopes (Sequence[str]): A list of OAuth2 scopes to attach to requests.
            client_config (dict):
                A dictionary for call options for each method. See
                :func:`google.gax.construct_settings` for the structure of
                this data. Falls back to the default config if not specified
                or the specified config is missing data points.
            lib_name (str): The API library software used for calling
                the service. (Unless you are writing an API client itself,
                leave this as default.)
            lib_version (str): The API library software version used
                for calling the service. (Unless you are writing an API client
                itself, leave this as default.)
            metrics_headers (dict): A dictionary of values for tracking
                client library metrics. Ultimately serializes to a string
                (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be
                considered private.
        """
        # Unless the calling application specifically requested
        # OAuth scopes, request everything.
        if scopes is None:
            scopes = self._ALL_SCOPES

        # Initialize an empty client config, if none is set.
        if client_config is None:
            client_config = {}

        # Initialize metrics_headers as an ordered dictionary
        # (cuts down on cardinality of the resulting string slightly).
        metrics_headers = collections.OrderedDict(metrics_headers)
        metrics_headers['gl-python'] = platform.python_version()

        # The library may or may not be set, depending on what is
        # calling this client. Newer client libraries set the library name
        # and version.
        if lib_name:
            metrics_headers[lib_name] = lib_version

        # Finally, track the GAPIC package version.
        metrics_headers['gapic'] = pkg_resources.get_distribution(
            'google-cloud-firestore', ).version

        # Load the configuration defaults.
        defaults = api_callable.construct_settings(
            'google.firestore.admin.v1beta1.FirestoreAdmin',
            firestore_admin_client_config.config,
            client_config,
            config.STATUS_CODE_NAMES,
            metrics_headers=metrics_headers,
            page_descriptors=self._PAGE_DESCRIPTORS, )
        self.firestore_admin_stub = config.create_stub(
            firestore_admin_pb2.FirestoreAdminStub,
            channel=channel,
            service_path=self.SERVICE_ADDRESS,
            service_port=self.DEFAULT_SERVICE_PORT,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)

        self._create_index = api_callable.create_api_call(
            self.firestore_admin_stub.CreateIndex,
            settings=defaults['create_index'])
        self._list_indexes = api_callable.create_api_call(
            self.firestore_admin_stub.ListIndexes,
            settings=defaults['list_indexes'])
        self._get_index = api_callable.create_api_call(
            self.firestore_admin_stub.GetIndex, settings=defaults['get_index'])
        self._delete_index = api_callable.create_api_call(
            self.firestore_admin_stub.DeleteIndex,
            settings=defaults['delete_index'])

    # Service calls
    def create_index(self, parent, index, options=None):
        """
        Creates the specified index.
        A newly created index's initial state is ``CREATING``. On completion of the
        returned ``google.longrunning.Operation``, the state will be ``READY``.
        If the index already exists, the call will return an ``ALREADY_EXISTS``
        status.

        During creation, the process could result in an error, in which case the
        index will move to the ``ERROR`` state. The process can be recovered by
        fixing the data that caused the error, removing the index with
        ``delete``, then re-creating the index with
        ``create``.

        Indexes with a single field cannot be created.

        Example:
            >>> from google.cloud import firestore_v1beta1
            >>>
            >>> client = firestore_v1beta1.FirestoreAdminClient()
            >>>
            >>> parent = client.database_path('[PROJECT]', '[DATABASE]')
            >>> index = {}
            >>>
            >>> response = client.create_index(parent, index)

        Args:
            parent (str): The name of the database this index will apply to. For example:
                ``projects/{project_id}/databases/{database_id}``
            index (Union[dict, ~google.cloud.firestore_v1beta1.types.Index]): The index to create. The name and state should not be specified.
                Certain single field indexes cannot be created or deleted.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.Index`
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.firestore_v1beta1.types.Operation` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = firestore_admin_pb2.CreateIndexRequest(
            parent=parent, index=index)
        return self._create_index(request, options)

    def list_indexes(self, parent, filter_=None, page_size=None, options=None):
        """
        Lists the indexes that match the specified filters.

        Example:
            >>> from google.cloud import firestore_v1beta1
            >>> from google.gax import CallOptions, INITIAL_PAGE
            >>>
            >>> client = firestore_v1beta1.FirestoreAdminClient()
            >>>
            >>> parent = client.database_path('[PROJECT]', '[DATABASE]')
            >>>
            >>>
            >>> # Iterate over all results
            >>> for element in client.list_indexes(parent):
            ...     # process element
            ...     pass
            >>>
            >>> # Or iterate over results one page at a time
            >>> for page in client.list_indexes(parent, options=CallOptions(page_token=INITIAL_PAGE)):
            ...     for element in page:
            ...         # process element
            ...         pass

        Args:
            parent (str): The database name. For example:
                ``projects/{project_id}/databases/{database_id}``
            filter_ (str)
            page_size (int): The maximum number of resources contained in the
                underlying API response. If page streaming is performed per-
                resource, this parameter does not affect the return value. If page
                streaming is performed per-page, this determines the maximum number
                of resources in a page.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.gax.PageIterator` instance. By default, this
            is an iterable of :class:`~google.cloud.firestore_v1beta1.types.Index` instances.
            This object can also be configured to iterate over the pages
            of the response through the `options` parameter.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = firestore_admin_pb2.ListIndexesRequest(
            parent=parent, filter=filter_, page_size=page_size)
        return self._list_indexes(request, options)

    def get_index(self, name, options=None):
        """
        Gets an index.

        Example:
            >>> from google.cloud import firestore_v1beta1
            >>>
            >>> client = firestore_v1beta1.FirestoreAdminClient()
            >>>
            >>> name = client.index_path('[PROJECT]', '[DATABASE]', '[INDEX]')
            >>>
            >>> response = client.get_index(name)

        Args:
            name (str): The name of the index. For example:
                ``projects/{project_id}/databases/{database_id}/indexes/{index_id}``
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.firestore_v1beta1.types.Index` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = firestore_admin_pb2.GetIndexRequest(name=name)
        return self._get_index(request, options)

    def delete_index(self, name, options=None):
        """
        Deletes an index.

        Example:
            >>> from google.cloud import firestore_v1beta1
            >>>
            >>> client = firestore_v1beta1.FirestoreAdminClient()
            >>>
            >>> name = client.index_path('[PROJECT]', '[DATABASE]', '[INDEX]')
            >>>
            >>> client.delete_index(name)

        Args:
            name (str): The index name. For example:
                ``projects/{project_id}/databases/{database_id}/indexes/{index_id}``
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = firestore_admin_pb2.DeleteIndexRequest(name=name)
        self._delete_index(request, options)
class GroupServiceClient(object):
    """
    The Group API lets you inspect and manage your
    `groups <https://cloud.google.comgoogle.monitoring.v3.Group>`_.

    A group is a named filter that is used to identify
    a collection of monitored resources. Groups are typically used to
    mirror the physical and/or logical topology of the environment.
    Because group membership is computed dynamically, monitored
    resources that are started in the future are automatically placed
    in matching groups. By using a group to name monitored resources in,
    for example, an alert policy, the target of that alert policy is
    updated automatically as monitored resources are added and removed
    from the infrastructure.
    """

    SERVICE_ADDRESS = 'monitoring.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _PAGE_DESCRIPTORS = {
        'list_groups': _PageDesc('page_token', 'next_page_token', 'group'),
        'list_group_members': _PageDesc('page_token', 'next_page_token',
                                        'members')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = (
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/monitoring',
        'https://www.googleapis.com/auth/monitoring.read',
        'https://www.googleapis.com/auth/monitoring.write',
    )

    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')
    _GROUP_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/groups/{group}')

    @classmethod
    def project_path(cls, project):
        """Returns a fully-qualified project resource name string."""
        return cls._PROJECT_PATH_TEMPLATE.render({
            'project': project,
        })

    @classmethod
    def group_path(cls, project, group):
        """Returns a fully-qualified group resource name string."""
        return cls._GROUP_PATH_TEMPLATE.render({
            'project': project,
            'group': group,
        })

    @classmethod
    def match_project_from_project_name(cls, project_name):
        """Parses the project from a project resource.

        Args:
          project_name (string): A fully-qualified path representing a project
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')

    @classmethod
    def match_project_from_group_name(cls, group_name):
        """Parses the project from a group resource.

        Args:
          group_name (string): A fully-qualified path representing a group
            resource.

        Returns:
          A string representing the project.
        """
        return cls._GROUP_PATH_TEMPLATE.match(group_name).get('project')

    @classmethod
    def match_group_from_group_name(cls, group_name):
        """Parses the group from a group resource.

        Args:
          group_name (string): A fully-qualified path representing a group
            resource.

        Returns:
          A string representing the group.
        """
        return cls._GROUP_PATH_TEMPLATE.match(group_name).get('group')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 credentials=None,
                 ssl_credentials=None,
                 scopes=None,
                 client_config=None,
                 app_name=None,
                 app_version='',
                 lib_name=None,
                 lib_version='',
                 metrics_headers=()):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          credentials (object): The authorization credentials to attach to
            requests. These credentials identify this application to the
            service.
          ssl_credentials (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          scopes (list[string]): A list of OAuth2 scopes to attach to requests.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          app_name (string): The name of the application calling
            the service. Recommended for analytics purposes.
          app_version (string): The version of the application calling
            the service. Recommended for analytics purposes.
          lib_name (string): The API library software used for calling
            the service. (Unless you are writing an API client itself,
            leave this as default.)
          lib_version (string): The API library software version used
            for calling the service. (Unless you are writing an API client
            itself, leave this as default.)
          metrics_headers (dict): A dictionary of values for tracking
            client library metrics. Ultimately serializes to a string
            (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be
            considered private.

        Returns:
          A GroupServiceClient object.
        """
        # Unless the calling application specifically requested
        # OAuth scopes, request everything.
        if scopes is None:
            scopes = self._ALL_SCOPES

        # Initialize an empty client config, if none is set.
        if client_config is None:
            client_config = {}

        # Initialize metrics_headers as an ordered dictionary
        # (cuts down on cardinality of the resulting string slightly).
        metrics_headers = collections.OrderedDict(metrics_headers)
        metrics_headers['gl-python'] = platform.python_version()

        # The library may or may not be set, depending on what is
        # calling this client. Newer client libraries set the library name
        # and version.
        if lib_name:
            metrics_headers[lib_name] = lib_version

        # Finally, track the GAPIC package version.
        metrics_headers['gapic'] = pkg_resources.get_distribution(
            'gapic-google-cloud-monitoring-v3', ).version

        # Load the configuration defaults.
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'group_service_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.monitoring.v3.GroupService',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            metrics_headers=metrics_headers,
            page_descriptors=self._PAGE_DESCRIPTORS,
        )
        self.group_service_stub = config.create_stub(
            group_service_pb2.GroupServiceStub,
            channel=channel,
            service_path=service_path,
            service_port=port,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)

        self._list_groups = api_callable.create_api_call(
            self.group_service_stub.ListGroups,
            settings=defaults['list_groups'])
        self._get_group = api_callable.create_api_call(
            self.group_service_stub.GetGroup, settings=defaults['get_group'])
        self._create_group = api_callable.create_api_call(
            self.group_service_stub.CreateGroup,
            settings=defaults['create_group'])
        self._update_group = api_callable.create_api_call(
            self.group_service_stub.UpdateGroup,
            settings=defaults['update_group'])
        self._delete_group = api_callable.create_api_call(
            self.group_service_stub.DeleteGroup,
            settings=defaults['delete_group'])
        self._list_group_members = api_callable.create_api_call(
            self.group_service_stub.ListGroupMembers,
            settings=defaults['list_group_members'])

    # Service calls
    def list_groups(self,
                    name,
                    children_of_group=None,
                    ancestors_of_group=None,
                    descendants_of_group=None,
                    page_size=0,
                    options=None):
        """
        Lists the existing groups.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import group_service_client
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = group_service_client.GroupServiceClient()
          >>> name = api.project_path('[PROJECT]')
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_groups(name):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_groups(name, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          name (string): The project whose groups are to be listed. The format is
            ``\"projects/{project_id_or_number}\"``.
          children_of_group (string): A group name: ``\"projects/{project_id_or_number}/groups/{group_id}\"``.
            Returns groups whose ``parentName`` field contains the group
            name.  If no groups have this parent, the results are empty.
          ancestors_of_group (string): A group name: ``\"projects/{project_id_or_number}/groups/{group_id}\"``.
            Returns groups that are ancestors of the specified group.
            The groups are returned in order, starting with the immediate parent and
            ending with the most distant ancestor.  If the specified group has no
            immediate parent, the results are empty.
          descendants_of_group (string): A group name: ``\"projects/{project_id_or_number}/groups/{group_id}\"``.
            Returns the descendants of the specified group.  This is a superset of
            the results returned by the ``childrenOfGroup`` filter, and includes
            children-of-children, and so forth.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.cloud.proto.monitoring.v3.group_pb2.Group` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Sanity check: We have some fields which are mutually exclusive;
        # raise ValueError if more than one is sent.
        oneof.check_oneof(
            children_of_group=children_of_group,
            ancestors_of_group=ancestors_of_group,
            descendants_of_group=descendants_of_group,
        )

        # Create the request object.
        request = group_service_pb2.ListGroupsRequest(
            name=name,
            children_of_group=children_of_group,
            ancestors_of_group=ancestors_of_group,
            descendants_of_group=descendants_of_group,
            page_size=page_size)
        return self._list_groups(request, options)

    def get_group(self, name, options=None):
        """
        Gets a single group.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import group_service_client
          >>> api = group_service_client.GroupServiceClient()
          >>> name = api.group_path('[PROJECT]', '[GROUP]')
          >>> response = api.get_group(name)

        Args:
          name (string): The group to retrieve. The format is
            ``\"projects/{project_id_or_number}/groups/{group_id}\"``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.monitoring.v3.group_pb2.Group` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = group_service_pb2.GetGroupRequest(name=name)
        return self._get_group(request, options)

    def create_group(self, name, group, validate_only=False, options=None):
        """
        Creates a new group.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import group_service_client
          >>> from google.cloud.proto.monitoring.v3 import group_pb2
          >>> api = group_service_client.GroupServiceClient()
          >>> name = api.project_path('[PROJECT]')
          >>> group = group_pb2.Group()
          >>> response = api.create_group(name, group)

        Args:
          name (string): The project in which to create the group. The format is
            ``\"projects/{project_id_or_number}\"``.
          group (:class:`google.cloud.proto.monitoring.v3.group_pb2.Group`): A group definition. It is an error to define the ``name`` field because
            the system assigns the name.
          validate_only (bool): If true, validate this request but do not create the group.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.monitoring.v3.group_pb2.Group` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = group_service_pb2.CreateGroupRequest(
            name=name, group=group, validate_only=validate_only)
        return self._create_group(request, options)

    def update_group(self, group, validate_only=False, options=None):
        """
        Updates an existing group.
        You can change any group attributes except ``name``.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import group_service_client
          >>> from google.cloud.proto.monitoring.v3 import group_pb2
          >>> api = group_service_client.GroupServiceClient()
          >>> group = group_pb2.Group()
          >>> response = api.update_group(group)

        Args:
          group (:class:`google.cloud.proto.monitoring.v3.group_pb2.Group`): The new definition of the group.  All fields of the existing group,
            excepting ``name``, are replaced with the corresponding fields of this group.
          validate_only (bool): If true, validate this request but do not update the existing group.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.monitoring.v3.group_pb2.Group` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = group_service_pb2.UpdateGroupRequest(
            group=group, validate_only=validate_only)
        return self._update_group(request, options)

    def delete_group(self, name, options=None):
        """
        Deletes an existing group.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import group_service_client
          >>> api = group_service_client.GroupServiceClient()
          >>> name = api.group_path('[PROJECT]', '[GROUP]')
          >>> api.delete_group(name)

        Args:
          name (string): The group to delete. The format is
            ``\"projects/{project_id_or_number}/groups/{group_id}\"``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = group_service_pb2.DeleteGroupRequest(name=name)
        self._delete_group(request, options)

    def list_group_members(self,
                           name,
                           page_size=0,
                           filter_='',
                           interval=None,
                           options=None):
        """
        Lists the monitored resources that are members of a group.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import group_service_client
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = group_service_client.GroupServiceClient()
          >>> name = api.group_path('[PROJECT]', '[GROUP]')
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_group_members(name):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_group_members(name, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          name (string): The group whose members are listed. The format is
            ``\"projects/{project_id_or_number}/groups/{group_id}\"``.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          filter_ (string): An optional `list filter <https://cloud.google.com/monitoring/api/learn_more#filtering>`_ describing
            the members to be returned.  The filter may reference the type, labels, and
            metadata of monitored resources that comprise the group.
            For example, to return only resources representing Compute Engine VM
            instances, use this filter:

            ::

                resource.type = \"gce_instance\"
          interval (:class:`google.cloud.proto.monitoring.v3.common_pb2.TimeInterval`): An optional time interval for which results should be returned. Only
            members that were part of the group during the specified interval are
            included in the response.  If no interval is provided then the group
            membership over the last minute is returned.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.api.monitored_resource_pb2.MonitoredResource` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        if interval is None:
            interval = common_pb2.TimeInterval()
        # Create the request object.
        request = group_service_pb2.ListGroupMembersRequest(
            name=name, page_size=page_size, filter=filter_, interval=interval)
        return self._list_group_members(request, options)
Exemple #5
0
class LoggingServiceV2Client(object):
    """Service for ingesting and querying logs."""

    SERVICE_ADDRESS = 'logging.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _PAGE_DESCRIPTORS = {
        'list_log_entries':
        _PageDesc('page_token', 'next_page_token', 'entries'),
        'list_monitored_resource_descriptors':
        _PageDesc('page_token', 'next_page_token', 'resource_descriptors'),
        'list_logs':
        _PageDesc('page_token', 'next_page_token', 'log_names')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = ('https://www.googleapis.com/auth/cloud-platform',
                   'https://www.googleapis.com/auth/cloud-platform.read-only',
                   'https://www.googleapis.com/auth/logging.admin',
                   'https://www.googleapis.com/auth/logging.read',
                   'https://www.googleapis.com/auth/logging.write', )

    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')
    _LOG_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/logs/{log}')

    @classmethod
    def project_path(cls, project):
        """Returns a fully-qualified project resource name string."""
        return cls._PROJECT_PATH_TEMPLATE.render({
            'project': project,
        })

    @classmethod
    def log_path(cls, project, log):
        """Returns a fully-qualified log resource name string."""
        return cls._LOG_PATH_TEMPLATE.render({
            'project': project,
            'log': log,
        })

    @classmethod
    def match_project_from_project_name(cls, project_name):
        """Parses the project from a project resource.

        Args:
          project_name (string): A fully-qualified path representing a project
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')

    @classmethod
    def match_project_from_log_name(cls, log_name):
        """Parses the project from a log resource.

        Args:
          log_name (string): A fully-qualified path representing a log
            resource.

        Returns:
          A string representing the project.
        """
        return cls._LOG_PATH_TEMPLATE.match(log_name).get('project')

    @classmethod
    def match_log_from_log_name(cls, log_name):
        """Parses the log from a log resource.

        Args:
          log_name (string): A fully-qualified path representing a log
            resource.

        Returns:
          A string representing the log.
        """
        return cls._LOG_PATH_TEMPLATE.match(log_name).get('log')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 credentials=None,
                 ssl_credentials=None,
                 scopes=None,
                 client_config=None,
                 app_name=None,
                 app_version='',
                 lib_name=None,
                 lib_version='',
                 metrics_headers=()):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          credentials (object): The authorization credentials to attach to
            requests. These credentials identify this application to the
            service.
          ssl_credentials (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          scopes (list[string]): A list of OAuth2 scopes to attach to requests.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          app_name (string): The name of the application calling
            the service. Recommended for analytics purposes.
          app_version (string): The version of the application calling
            the service. Recommended for analytics purposes.
          lib_name (string): The API library software used for calling
            the service. (Unless you are writing an API client itself,
            leave this as default.)
          lib_version (string): The API library software version used
            for calling the service. (Unless you are writing an API client
            itself, leave this as default.)
          metrics_headers (dict): A dictionary of values for tracking
            client library metrics. Ultimately serializes to a string
            (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be
            considered private.

        Returns:
          A LoggingServiceV2Client object.
        """
        # Unless the calling application specifically requested
        # OAuth scopes, request everything.
        if scopes is None:
            scopes = self._ALL_SCOPES

        # Initialize an empty client config, if none is set.
        if client_config is None:
            client_config = {}

        # Initialize metrics_headers as an ordered dictionary
        # (cuts down on cardinality of the resulting string slightly).
        metrics_headers = collections.OrderedDict(metrics_headers)
        metrics_headers['gl-python'] = platform.python_version()

        # The library may or may not be set, depending on what is
        # calling this client. Newer client libraries set the library name
        # and version.
        if lib_name:
            metrics_headers[lib_name] = lib_version

        # Finally, track the GAPIC package version.
        metrics_headers['gapic'] = pkg_resources.get_distribution(
            'gapic-google-cloud-logging-v2', ).version

        # Load the configuration defaults.
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'logging_service_v2_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.logging.v2.LoggingServiceV2',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            metrics_headers=metrics_headers,
            page_descriptors=self._PAGE_DESCRIPTORS, )
        self.logging_service_v2_stub = config.create_stub(
            logging_pb2.LoggingServiceV2Stub,
            channel=channel,
            service_path=service_path,
            service_port=port,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)

        self._delete_log = api_callable.create_api_call(
            self.logging_service_v2_stub.DeleteLog,
            settings=defaults['delete_log'])
        self._write_log_entries = api_callable.create_api_call(
            self.logging_service_v2_stub.WriteLogEntries,
            settings=defaults['write_log_entries'])
        self._list_log_entries = api_callable.create_api_call(
            self.logging_service_v2_stub.ListLogEntries,
            settings=defaults['list_log_entries'])
        self._list_monitored_resource_descriptors = api_callable.create_api_call(
            self.logging_service_v2_stub.ListMonitoredResourceDescriptors,
            settings=defaults['list_monitored_resource_descriptors'])
        self._list_logs = api_callable.create_api_call(
            self.logging_service_v2_stub.ListLogs,
            settings=defaults['list_logs'])

    # Service calls
    def delete_log(self, log_name, options=None):
        """
        Deletes all the log entries in a log.
        The log reappears if it receives new entries.
        Log entries written shortly before the delete operation might not be
        deleted.

        Example:
          >>> from google.cloud.gapic.logging.v2 import logging_service_v2_client
          >>> client = logging_service_v2_client.LoggingServiceV2Client()
          >>> log_name = client.log_path('[PROJECT]', '[LOG]')
          >>> client.delete_log(log_name)

        Args:
          log_name (string): Required. The resource name of the log to delete:

            ::

                \"projects/[PROJECT_ID]/logs/[LOG_ID]\"
                \"organizations/[ORGANIZATION_ID]/logs/[LOG_ID]\"
                \"billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]\"
                \"folders/[FOLDER_ID]/logs/[LOG_ID]\"

            ``[LOG_ID]`` must be URL-encoded. For example,
            ``\"projects/my-project-id/logs/syslog\"``,
            ``\"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity\"``.
            For more information about log names, see
            ``LogEntry``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = logging_pb2.DeleteLogRequest(log_name=log_name)
        self._delete_log(request, options)

    def write_log_entries(self,
                          entries,
                          log_name=None,
                          resource=None,
                          labels=None,
                          partial_success=None,
                          options=None):
        """
        Writes log entries to Stackdriver Logging.

        Example:
          >>> from google.cloud.gapic.logging.v2 import logging_service_v2_client
          >>> client = logging_service_v2_client.LoggingServiceV2Client()
          >>> entries = []
          >>> response = client.write_log_entries(entries)

        Args:
          entries (list[:class:`google.cloud.proto.logging.v2.log_entry_pb2.LogEntry`]): Required.  The log entries to write. Values supplied for the fields
            ``log_name``, ``resource``, and ``labels`` in this ``entries.write`` request are
            inserted into those log entries in this list that do not provide their own
            values.

            Stackdriver Logging also creates and inserts values for ``timestamp`` and
            ``insert_id`` if the entries do not provide them. The created ``insert_id`` for
            the N'th entry in this list will be greater than earlier entries and less
            than later entries.  Otherwise, the order of log entries in this list does
            not matter.

            To improve throughput and to avoid exceeding the
            `quota limit <https://cloud.google.com/logging/quota-policy>`_ for calls to ``entries.write``,
            you should write multiple log entries at once rather than
            calling this method for each individual log entry.
          log_name (string): Optional. A default log resource name that is assigned to all log entries
            in ``entries`` that do not specify a value for ``log_name``:

            ::

                \"projects/[PROJECT_ID]/logs/[LOG_ID]\"
                \"organizations/[ORGANIZATION_ID]/logs/[LOG_ID]\"
                \"billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]\"
                \"folders/[FOLDER_ID]/logs/[LOG_ID]\"

            ``[LOG_ID]`` must be URL-encoded. For example,
            ``\"projects/my-project-id/logs/syslog\"`` or
            ``\"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity\"``.
            For more information about log names, see
            ``LogEntry``.
          resource (:class:`google.api.monitored_resource_pb2.MonitoredResource`): Optional. A default monitored resource object that is assigned to all log
            entries in ``entries`` that do not specify a value for ``resource``. Example:

            ::

                { \"type\": \"gce_instance\",
                  \"labels\": {
                    \"zone\": \"us-central1-a\", \"instance_id\": \"00000000000000000000\" }}

            See ``LogEntry``.
          labels (dict[string -> string]): Optional. Default labels that are added to the ``labels`` field of all log
            entries in ``entries``. If a log entry already has a label with the same key
            as a label in this parameter, then the log entry's label is not changed.
            See ``LogEntry``.
          partial_success (bool): Optional. Whether valid entries should be written even if some other
            entries fail due to INVALID_ARGUMENT or PERMISSION_DENIED errors. If any
            entry is not written, then the response status is the error associated
            with one of the failed entries and the response includes error details
            keyed by the entries' zero-based index in the ``entries.write`` method.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.logging.v2.logging_pb2.WriteLogEntriesResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = logging_pb2.WriteLogEntriesRequest(
            entries=entries,
            log_name=log_name,
            resource=resource,
            labels=labels,
            partial_success=partial_success)
        return self._write_log_entries(request, options)

    def list_log_entries(self,
                         resource_names,
                         project_ids=None,
                         filter_=None,
                         order_by=None,
                         page_size=None,
                         options=None):
        """
        Lists log entries.  Use this method to retrieve log entries from
        Stackdriver Logging.  For ways to export log entries, see
        `Exporting Logs <https://cloud.google.com/logging/docs/export>`_.

        Example:
          >>> from google.cloud.gapic.logging.v2 import logging_service_v2_client
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> client = logging_service_v2_client.LoggingServiceV2Client()
          >>> resource_names = []
          >>>
          >>> # Iterate over all results
          >>> for element in client.list_log_entries(resource_names):
          >>>     # process element
          >>>     pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in client.list_log_entries(resource_names, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>     for element in page:
          >>>         # process element
          >>>         pass

        Args:
          resource_names (list[string]): Required. Names of one or more parent resources from which to
            retrieve log entries:

            ::

                \"projects/[PROJECT_ID]\"
                \"organizations/[ORGANIZATION_ID]\"
                \"billingAccounts/[BILLING_ACCOUNT_ID]\"
                \"folders/[FOLDER_ID]\"

            Projects listed in the ``project_ids`` field are added to this list.
          project_ids (list[string]): Deprecated. Use ``resource_names`` instead.  One or more project identifiers
            or project numbers from which to retrieve log entries.  Example:
            ``\"my-project-1A\"``. If present, these project identifiers are converted to
            resource name format and added to the list of resources in
            ``resource_names``.
          filter_ (string): Optional. A filter that chooses which log entries to return.  See [Advanced
            Logs Filters](/logging/docs/view/advanced_filters).  Only log entries that
            match the filter are returned.  An empty filter matches all log entries in
            the resources listed in ``resource_names``. Referencing a parent resource
            that is not listed in ``resource_names`` will cause the filter to return no
            results.
            The maximum length of the filter is 20000 characters.
          order_by (string): Optional. How the results should be sorted.  Presently, the only permitted
            values are ``\"timestamp asc\"`` (default) and ``\"timestamp desc\"``. The first
            option returns entries in order of increasing values of
            ``LogEntry.timestamp`` (oldest first), and the second option returns entries
            in order of decreasing timestamps (newest first).  Entries with equal
            timestamps are returned in order of their ``insert_id`` values.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.cloud.proto.logging.v2.log_entry_pb2.LogEntry` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = logging_pb2.ListLogEntriesRequest(
            resource_names=resource_names,
            project_ids=project_ids,
            filter=filter_,
            order_by=order_by,
            page_size=page_size)
        return self._list_log_entries(request, options)

    def list_monitored_resource_descriptors(self, page_size=None,
                                            options=None):
        """
        Lists the descriptors for monitored resource types used by Stackdriver
        Logging.

        Example:
          >>> from google.cloud.gapic.logging.v2 import logging_service_v2_client
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> client = logging_service_v2_client.LoggingServiceV2Client()
          >>>
          >>> # Iterate over all results
          >>> for element in client.list_monitored_resource_descriptors():
          >>>     # process element
          >>>     pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in client.list_monitored_resource_descriptors(options=CallOptions(page_token=INITIAL_PAGE)):
          >>>     for element in page:
          >>>         # process element
          >>>         pass

        Args:
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.api.monitored_resource_pb2.MonitoredResourceDescriptor` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = logging_pb2.ListMonitoredResourceDescriptorsRequest(
            page_size=page_size)
        return self._list_monitored_resource_descriptors(request, options)

    def list_logs(self, parent, page_size=None, options=None):
        """
        Lists the logs in projects, organizations, folders, or billing accounts.
        Only logs that have entries are listed.

        Example:
          >>> from google.cloud.gapic.logging.v2 import logging_service_v2_client
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> client = logging_service_v2_client.LoggingServiceV2Client()
          >>> parent = client.project_path('[PROJECT]')
          >>>
          >>> # Iterate over all results
          >>> for element in client.list_logs(parent):
          >>>     # process element
          >>>     pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in client.list_logs(parent, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>     for element in page:
          >>>         # process element
          >>>         pass

        Args:
          parent (string): Required. The resource name that owns the logs:

            ::

                \"projects/[PROJECT_ID]\"
                \"organizations/[ORGANIZATION_ID]\"
                \"billingAccounts/[BILLING_ACCOUNT_ID]\"
                \"folders/[FOLDER_ID]\"
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of string instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = logging_pb2.ListLogsRequest(
            parent=parent, page_size=page_size)
        return self._list_logs(request, options)
class FirestoreClient(object):
    """
    The Cloud Firestore service.

    This service exposes several types of comparable timestamps:

    *    ``create_time`` - The time at which a document was created. Changes only
    ::

         when a document is deleted, then re-created. Increases in a strict
          monotonic fashion.
    *    ``update_time`` - The time at which a document was last updated. Changes
    ::

         every time a document is modified. Does not change when a write results
         in no modifications. Increases in a strict monotonic fashion.
    *    ``read_time`` - The time at which a particular state was observed. Used
    ::

         to denote a consistent snapshot of the database or the time at which a
         Document was observed to not exist.
    *    ``commit_time`` - The time at which the writes in a transaction were
    ::

         committed. Any read with an equal or greater `read_time` is guaranteed
         to see the effects of the transaction.
    """

    SERVICE_ADDRESS = 'firestore.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _PAGE_DESCRIPTORS = {
        'list_documents':
        _PageDesc('page_token', 'next_page_token', 'documents'),
        'list_collection_ids':
        _PageDesc('page_token', 'next_page_token', 'collection_ids')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = (
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/datastore',
    )

    _DATABASE_ROOT_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/databases/{database}')
    _DOCUMENT_ROOT_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/databases/{database}/documents')
    _DOCUMENT_PATH_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/databases/{database}/documents/{document_path=**}')
    _ANY_PATH_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/databases/{database}/documents/{document}/{any_path=**}'
    )

    @classmethod
    def database_root_path(cls, project, database):
        """Returns a fully-qualified database_root resource name string."""
        return cls._DATABASE_ROOT_PATH_TEMPLATE.render({
            'project': project,
            'database': database,
        })

    @classmethod
    def document_root_path(cls, project, database):
        """Returns a fully-qualified document_root resource name string."""
        return cls._DOCUMENT_ROOT_PATH_TEMPLATE.render({
            'project': project,
            'database': database,
        })

    @classmethod
    def document_path_path(cls, project, database, document_path):
        """Returns a fully-qualified document_path resource name string."""
        return cls._DOCUMENT_PATH_PATH_TEMPLATE.render({
            'project':
            project,
            'database':
            database,
            'document_path':
            document_path,
        })

    @classmethod
    def any_path_path(cls, project, database, document, any_path):
        """Returns a fully-qualified any_path resource name string."""
        return cls._ANY_PATH_PATH_TEMPLATE.render({
            'project': project,
            'database': database,
            'document': document,
            'any_path': any_path,
        })

    @classmethod
    def match_project_from_database_root_name(cls, database_root_name):
        """Parses the project from a database_root resource.

        Args:
            database_root_name (str): A fully-qualified path representing a database_root
                resource.

        Returns:
            A string representing the project.
        """
        return cls._DATABASE_ROOT_PATH_TEMPLATE.match(database_root_name).get(
            'project')

    @classmethod
    def match_database_from_database_root_name(cls, database_root_name):
        """Parses the database from a database_root resource.

        Args:
            database_root_name (str): A fully-qualified path representing a database_root
                resource.

        Returns:
            A string representing the database.
        """
        return cls._DATABASE_ROOT_PATH_TEMPLATE.match(database_root_name).get(
            'database')

    @classmethod
    def match_project_from_document_root_name(cls, document_root_name):
        """Parses the project from a document_root resource.

        Args:
            document_root_name (str): A fully-qualified path representing a document_root
                resource.

        Returns:
            A string representing the project.
        """
        return cls._DOCUMENT_ROOT_PATH_TEMPLATE.match(document_root_name).get(
            'project')

    @classmethod
    def match_database_from_document_root_name(cls, document_root_name):
        """Parses the database from a document_root resource.

        Args:
            document_root_name (str): A fully-qualified path representing a document_root
                resource.

        Returns:
            A string representing the database.
        """
        return cls._DOCUMENT_ROOT_PATH_TEMPLATE.match(document_root_name).get(
            'database')

    @classmethod
    def match_project_from_document_path_name(cls, document_path_name):
        """Parses the project from a document_path resource.

        Args:
            document_path_name (str): A fully-qualified path representing a document_path
                resource.

        Returns:
            A string representing the project.
        """
        return cls._DOCUMENT_PATH_PATH_TEMPLATE.match(document_path_name).get(
            'project')

    @classmethod
    def match_database_from_document_path_name(cls, document_path_name):
        """Parses the database from a document_path resource.

        Args:
            document_path_name (str): A fully-qualified path representing a document_path
                resource.

        Returns:
            A string representing the database.
        """
        return cls._DOCUMENT_PATH_PATH_TEMPLATE.match(document_path_name).get(
            'database')

    @classmethod
    def match_document_path_from_document_path_name(cls, document_path_name):
        """Parses the document_path from a document_path resource.

        Args:
            document_path_name (str): A fully-qualified path representing a document_path
                resource.

        Returns:
            A string representing the document_path.
        """
        return cls._DOCUMENT_PATH_PATH_TEMPLATE.match(document_path_name).get(
            'document_path')

    @classmethod
    def match_project_from_any_path_name(cls, any_path_name):
        """Parses the project from a any_path resource.

        Args:
            any_path_name (str): A fully-qualified path representing a any_path
                resource.

        Returns:
            A string representing the project.
        """
        return cls._ANY_PATH_PATH_TEMPLATE.match(any_path_name).get('project')

    @classmethod
    def match_database_from_any_path_name(cls, any_path_name):
        """Parses the database from a any_path resource.

        Args:
            any_path_name (str): A fully-qualified path representing a any_path
                resource.

        Returns:
            A string representing the database.
        """
        return cls._ANY_PATH_PATH_TEMPLATE.match(any_path_name).get('database')

    @classmethod
    def match_document_from_any_path_name(cls, any_path_name):
        """Parses the document from a any_path resource.

        Args:
            any_path_name (str): A fully-qualified path representing a any_path
                resource.

        Returns:
            A string representing the document.
        """
        return cls._ANY_PATH_PATH_TEMPLATE.match(any_path_name).get('document')

    @classmethod
    def match_any_path_from_any_path_name(cls, any_path_name):
        """Parses the any_path from a any_path resource.

        Args:
            any_path_name (str): A fully-qualified path representing a any_path
                resource.

        Returns:
            A string representing the any_path.
        """
        return cls._ANY_PATH_PATH_TEMPLATE.match(any_path_name).get('any_path')

    def __init__(self,
                 channel=None,
                 credentials=None,
                 ssl_credentials=None,
                 scopes=None,
                 client_config=None,
                 lib_name=None,
                 lib_version='',
                 metrics_headers=()):
        """Constructor.

        Args:
            channel (~grpc.Channel): A ``Channel`` instance through
                which to make calls.
            credentials (~google.auth.credentials.Credentials): The authorization
                credentials to attach to requests. These credentials identify this
                application to the service.
            ssl_credentials (~grpc.ChannelCredentials): A
                ``ChannelCredentials`` instance for use with an SSL-enabled
                channel.
            scopes (Sequence[str]): A list of OAuth2 scopes to attach to requests.
            client_config (dict):
                A dictionary for call options for each method. See
                :func:`google.gax.construct_settings` for the structure of
                this data. Falls back to the default config if not specified
                or the specified config is missing data points.
            lib_name (str): The API library software used for calling
                the service. (Unless you are writing an API client itself,
                leave this as default.)
            lib_version (str): The API library software version used
                for calling the service. (Unless you are writing an API client
                itself, leave this as default.)
            metrics_headers (dict): A dictionary of values for tracking
                client library metrics. Ultimately serializes to a string
                (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be
                considered private.
        """
        # Unless the calling application specifically requested
        # OAuth scopes, request everything.
        if scopes is None:
            scopes = self._ALL_SCOPES

        # Initialize an empty client config, if none is set.
        if client_config is None:
            client_config = {}

        # Initialize metrics_headers as an ordered dictionary
        # (cuts down on cardinality of the resulting string slightly).
        metrics_headers = collections.OrderedDict(metrics_headers)
        metrics_headers['gl-python'] = platform.python_version()

        # The library may or may not be set, depending on what is
        # calling this client. Newer client libraries set the library name
        # and version.
        if lib_name:
            metrics_headers[lib_name] = lib_version

        # Finally, track the GAPIC package version.
        metrics_headers['gapic'] = pkg_resources.get_distribution(
            'google-cloud-firestore', ).version

        # Load the configuration defaults.
        defaults = api_callable.construct_settings(
            'google.firestore.v1beta1.Firestore',
            firestore_client_config.config,
            client_config,
            config.STATUS_CODE_NAMES,
            metrics_headers=metrics_headers,
            page_descriptors=self._PAGE_DESCRIPTORS,
        )
        self.firestore_stub = config.create_stub(
            firestore_pb2.FirestoreStub,
            channel=channel,
            service_path=self.SERVICE_ADDRESS,
            service_port=self.DEFAULT_SERVICE_PORT,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)

        self._get_document = api_callable.create_api_call(
            self.firestore_stub.GetDocument, settings=defaults['get_document'])
        self._list_documents = api_callable.create_api_call(
            self.firestore_stub.ListDocuments,
            settings=defaults['list_documents'])
        self._create_document = api_callable.create_api_call(
            self.firestore_stub.CreateDocument,
            settings=defaults['create_document'])
        self._update_document = api_callable.create_api_call(
            self.firestore_stub.UpdateDocument,
            settings=defaults['update_document'])
        self._delete_document = api_callable.create_api_call(
            self.firestore_stub.DeleteDocument,
            settings=defaults['delete_document'])
        self._batch_get_documents = api_callable.create_api_call(
            self.firestore_stub.BatchGetDocuments,
            settings=defaults['batch_get_documents'])
        self._begin_transaction = api_callable.create_api_call(
            self.firestore_stub.BeginTransaction,
            settings=defaults['begin_transaction'])
        self._commit = api_callable.create_api_call(
            self.firestore_stub.Commit, settings=defaults['commit'])
        self._rollback = api_callable.create_api_call(
            self.firestore_stub.Rollback, settings=defaults['rollback'])
        self._run_query = api_callable.create_api_call(
            self.firestore_stub.RunQuery, settings=defaults['run_query'])
        self._write = api_callable.create_api_call(self.firestore_stub.Write,
                                                   settings=defaults['write'])
        self._listen = api_callable.create_api_call(
            self.firestore_stub.Listen, settings=defaults['listen'])
        self._list_collection_ids = api_callable.create_api_call(
            self.firestore_stub.ListCollectionIds,
            settings=defaults['list_collection_ids'])

    # Service calls
    def get_document(self,
                     name,
                     mask=None,
                     transaction=None,
                     read_time=None,
                     options=None):
        """
        Gets a single document.

        Example:
            >>> from google.cloud import firestore_v1beta1
            >>>
            >>> client = firestore_v1beta1.FirestoreClient()
            >>>
            >>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
            >>>
            >>> response = client.get_document(name)

        Args:
            name (str): The resource name of the Document to get. In the format:
                ``projects/{project_id}/databases/{database_id}/documents/{document_path}``.
            mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields.

                If the document has a field that is not present in this mask, that field
                will not be returned in the response.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
            transaction (bytes): Reads the document in a transaction.
            read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads the version of the document at the given time.
                This may not be older than 60 seconds.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.Timestamp`
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.firestore_v1beta1.types.Document` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        # Sanity check: We have some fields which are mutually exclusive;
        # raise ValueError if more than one is sent.
        oneof.check_oneof(
            transaction=transaction,
            read_time=read_time,
        )

        request = firestore_pb2.GetDocumentRequest(name=name,
                                                   mask=mask,
                                                   transaction=transaction,
                                                   read_time=read_time)
        return self._get_document(request, options)

    def list_documents(self,
                       parent,
                       collection_id,
                       page_size=None,
                       order_by=None,
                       mask=None,
                       transaction=None,
                       read_time=None,
                       show_missing=None,
                       options=None):
        """
        Lists documents.

        Example:
            >>> from google.cloud import firestore_v1beta1
            >>> from google.gax import CallOptions, INITIAL_PAGE
            >>>
            >>> client = firestore_v1beta1.FirestoreClient()
            >>>
            >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
            >>> collection_id = ''
            >>>
            >>>
            >>> # Iterate over all results
            >>> for element in client.list_documents(parent, collection_id):
            ...     # process element
            ...     pass
            >>>
            >>> # Or iterate over results one page at a time
            >>> for page in client.list_documents(parent, collection_id, options=CallOptions(page_token=INITIAL_PAGE)):
            ...     for element in page:
            ...         # process element
            ...         pass

        Args:
            parent (str): The parent resource name. In the format:
                ``projects/{project_id}/databases/{database_id}/documents`` or
                ``projects/{project_id}/databases/{database_id}/documents/{document_path}``.
                For example:
                ``projects/my-project/databases/my-database/documents`` or
                ``projects/my-project/databases/my-database/documents/chatrooms/my-chatroom``
            collection_id (str): The collection ID, relative to ``parent``, to list. For example: ``chatrooms``
                or ``messages``.
            page_size (int): The maximum number of resources contained in the
                underlying API response. If page streaming is performed per-
                resource, this parameter does not affect the return value. If page
                streaming is performed per-page, this determines the maximum number
                of resources in a page.
            order_by (str): The order to sort results by. For example: ``priority desc, name``.
            mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields.

                If a document has a field that is not present in this mask, that field
                will not be returned in the response.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
            transaction (bytes): Reads documents in a transaction.
            read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time.
                This may not be older than 60 seconds.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.Timestamp`
            show_missing (bool): If the list should show missing documents. A missing document is a
                document that does not exist but has sub-documents. These documents will
                be returned with a key but will not have fields, ``Document.create_time``,
                or ``Document.update_time`` set.

                Requests with ``show_missing`` may not specify ``where`` or
                ``order_by``.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.gax.PageIterator` instance. By default, this
            is an iterable of :class:`~google.cloud.firestore_v1beta1.types.Document` instances.
            This object can also be configured to iterate over the pages
            of the response through the `options` parameter.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        # Sanity check: We have some fields which are mutually exclusive;
        # raise ValueError if more than one is sent.
        oneof.check_oneof(
            transaction=transaction,
            read_time=read_time,
        )

        request = firestore_pb2.ListDocumentsRequest(
            parent=parent,
            collection_id=collection_id,
            page_size=page_size,
            order_by=order_by,
            mask=mask,
            transaction=transaction,
            read_time=read_time,
            show_missing=show_missing)
        return self._list_documents(request, options)

    def create_document(self,
                        parent,
                        collection_id,
                        document_id,
                        document,
                        mask=None,
                        options=None):
        """
        Creates a new document.

        Example:
            >>> from google.cloud import firestore_v1beta1
            >>>
            >>> client = firestore_v1beta1.FirestoreClient()
            >>>
            >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
            >>> collection_id = ''
            >>> document_id = ''
            >>> document = {}
            >>>
            >>> response = client.create_document(parent, collection_id, document_id, document)

        Args:
            parent (str): The parent resource. For example:
                ``projects/{project_id}/databases/{database_id}/documents`` or
                ``projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}``
            collection_id (str): The collection ID, relative to ``parent``, to list. For example: ``chatrooms``.
            document_id (str): The client-assigned document ID to use for this document.

                Optional. If not specified, an ID will be assigned by the service.
            document (Union[dict, ~google.cloud.firestore_v1beta1.types.Document]): The document to create. ``name`` must not be set.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.Document`
            mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields.

                If the document has a field that is not present in this mask, that field
                will not be returned in the response.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.firestore_v1beta1.types.Document` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = firestore_pb2.CreateDocumentRequest(
            parent=parent,
            collection_id=collection_id,
            document_id=document_id,
            document=document,
            mask=mask)
        return self._create_document(request, options)

    def update_document(self,
                        document,
                        update_mask,
                        mask=None,
                        current_document=None,
                        options=None):
        """
        Updates or inserts a document.

        Example:
            >>> from google.cloud import firestore_v1beta1
            >>>
            >>> client = firestore_v1beta1.FirestoreClient()
            >>>
            >>> document = {}
            >>> update_mask = {}
            >>>
            >>> response = client.update_document(document, update_mask)

        Args:
            document (Union[dict, ~google.cloud.firestore_v1beta1.types.Document]): The updated document.
                Creates the document if it does not already exist.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.Document`
            update_mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to update.
                None of the field paths in the mask may contain a reserved name.

                If the document exists on the server and has fields not referenced in the
                mask, they are left unchanged.
                Fields referenced in the mask, but not present in the input document, are
                deleted from the document on the server.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
            mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields.

                If the document has a field that is not present in this mask, that field
                will not be returned in the response.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
            current_document (Union[dict, ~google.cloud.firestore_v1beta1.types.Precondition]): An optional precondition on the document.
                The request will fail if this is set and not met by the target document.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.Precondition`
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.firestore_v1beta1.types.Document` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = firestore_pb2.UpdateDocumentRequest(
            document=document,
            update_mask=update_mask,
            mask=mask,
            current_document=current_document)
        return self._update_document(request, options)

    def delete_document(self, name, current_document=None, options=None):
        """
        Deletes a document.

        Example:
            >>> from google.cloud import firestore_v1beta1
            >>>
            >>> client = firestore_v1beta1.FirestoreClient()
            >>>
            >>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
            >>>
            >>> client.delete_document(name)

        Args:
            name (str): The resource name of the Document to delete. In the format:
                ``projects/{project_id}/databases/{database_id}/documents/{document_path}``.
            current_document (Union[dict, ~google.cloud.firestore_v1beta1.types.Precondition]): An optional precondition on the document.
                The request will fail if this is set and not met by the target document.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.Precondition`
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = firestore_pb2.DeleteDocumentRequest(
            name=name, current_document=current_document)
        self._delete_document(request, options)

    def batch_get_documents(self,
                            database,
                            documents,
                            mask=None,
                            transaction=None,
                            new_transaction=None,
                            read_time=None,
                            options=None):
        """
        Gets multiple documents.

        Documents returned by this method are not guaranteed to be returned in the
        same order that they were requested.

        Example:
            >>> from google.cloud import firestore_v1beta1
            >>>
            >>> client = firestore_v1beta1.FirestoreClient()
            >>>
            >>> database = client.database_root_path('[PROJECT]', '[DATABASE]')
            >>> documents = []
            >>>
            >>> for element in client.batch_get_documents(database, documents):
            ...     # process element
            ...     pass

        Args:
            database (str): The database name. In the format:
                ``projects/{project_id}/databases/{database_id}``.
            documents (list[str]): The names of the documents to retrieve. In the format:
                ``projects/{project_id}/databases/{database_id}/documents/{document_path}``.
                The request will fail if any of the document is not a child resource of the
                given ``database``. Duplicate names will be elided.
            mask (Union[dict, ~google.cloud.firestore_v1beta1.types.DocumentMask]): The fields to return. If not set, returns all fields.

                If a document has a field that is not present in this mask, that field will
                not be returned in the response.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.DocumentMask`
            transaction (bytes): Reads documents in a transaction.
            new_transaction (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): Starts a new transaction and reads the documents.
                Defaults to a read-only transaction.
                The new transaction ID will be returned as the first response in the
                stream.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions`
            read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time.
                This may not be older than 60 seconds.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.Timestamp`
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            Iterable[~google.cloud.firestore_v1beta1.types.BatchGetDocumentsResponse].

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        # Sanity check: We have some fields which are mutually exclusive;
        # raise ValueError if more than one is sent.
        oneof.check_oneof(
            transaction=transaction,
            new_transaction=new_transaction,
            read_time=read_time,
        )

        request = firestore_pb2.BatchGetDocumentsRequest(
            database=database,
            documents=documents,
            mask=mask,
            transaction=transaction,
            new_transaction=new_transaction,
            read_time=read_time)
        return self._batch_get_documents(request, options)

    def begin_transaction(self, database, options_=None, options=None):
        """
        Starts a new transaction.

        Example:
            >>> from google.cloud import firestore_v1beta1
            >>>
            >>> client = firestore_v1beta1.FirestoreClient()
            >>>
            >>> database = client.database_root_path('[PROJECT]', '[DATABASE]')
            >>>
            >>> response = client.begin_transaction(database)

        Args:
            database (str): The database name. In the format:
                ``projects/{project_id}/databases/{database_id}``.
            options_ (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): The options for the transaction.
                Defaults to a read-write transaction.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions`
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.firestore_v1beta1.types.BeginTransactionResponse` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = firestore_pb2.BeginTransactionRequest(database=database,
                                                        options=options_)
        return self._begin_transaction(request, options)

    def commit(self, database, writes, transaction=None, options=None):
        """
        Commits a transaction, while optionally updating documents.

        Example:
            >>> from google.cloud import firestore_v1beta1
            >>>
            >>> client = firestore_v1beta1.FirestoreClient()
            >>>
            >>> database = client.database_root_path('[PROJECT]', '[DATABASE]')
            >>> writes = []
            >>>
            >>> response = client.commit(database, writes)

        Args:
            database (str): The database name. In the format:
                ``projects/{project_id}/databases/{database_id}``.
            writes (list[Union[dict, ~google.cloud.firestore_v1beta1.types.Write]]): The writes to apply.

                Always executed atomically and in order.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.Write`
            transaction (bytes): If set, applies all writes in this transaction, and commits it.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.firestore_v1beta1.types.CommitResponse` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = firestore_pb2.CommitRequest(database=database,
                                              writes=writes,
                                              transaction=transaction)
        return self._commit(request, options)

    def rollback(self, database, transaction, options=None):
        """
        Rolls back a transaction.

        Example:
            >>> from google.cloud import firestore_v1beta1
            >>>
            >>> client = firestore_v1beta1.FirestoreClient()
            >>>
            >>> database = client.database_root_path('[PROJECT]', '[DATABASE]')
            >>> transaction = b''
            >>>
            >>> client.rollback(database, transaction)

        Args:
            database (str): The database name. In the format:
                ``projects/{project_id}/databases/{database_id}``.
            transaction (bytes): The transaction to roll back.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = firestore_pb2.RollbackRequest(database=database,
                                                transaction=transaction)
        self._rollback(request, options)

    def run_query(self,
                  parent,
                  structured_query=None,
                  transaction=None,
                  new_transaction=None,
                  read_time=None,
                  options=None):
        """
        Runs a query.

        Example:
            >>> from google.cloud import firestore_v1beta1
            >>>
            >>> client = firestore_v1beta1.FirestoreClient()
            >>>
            >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
            >>>
            >>> for element in client.run_query(parent):
            ...     # process element
            ...     pass

        Args:
            parent (str): The parent resource name. In the format:
                ``projects/{project_id}/databases/{database_id}/documents`` or
                ``projects/{project_id}/databases/{database_id}/documents/{document_path}``.
                For example:
                ``projects/my-project/databases/my-database/documents`` or
                ``projects/my-project/databases/my-database/documents/chatrooms/my-chatroom``
            structured_query (Union[dict, ~google.cloud.firestore_v1beta1.types.StructuredQuery]): A structured query.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.StructuredQuery`
            transaction (bytes): Reads documents in a transaction.
            new_transaction (Union[dict, ~google.cloud.firestore_v1beta1.types.TransactionOptions]): Starts a new transaction and reads the documents.
                Defaults to a read-only transaction.
                The new transaction ID will be returned as the first response in the
                stream.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.TransactionOptions`
            read_time (Union[dict, ~google.cloud.firestore_v1beta1.types.Timestamp]): Reads documents as they were at the given time.
                This may not be older than 60 seconds.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.firestore_v1beta1.types.Timestamp`
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            Iterable[~google.cloud.firestore_v1beta1.types.RunQueryResponse].

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        # Sanity check: We have some fields which are mutually exclusive;
        # raise ValueError if more than one is sent.
        oneof.check_oneof(structured_query=structured_query, )

        # Sanity check: We have some fields which are mutually exclusive;
        # raise ValueError if more than one is sent.
        oneof.check_oneof(
            transaction=transaction,
            new_transaction=new_transaction,
            read_time=read_time,
        )

        request = firestore_pb2.RunQueryRequest(
            parent=parent,
            structured_query=structured_query,
            transaction=transaction,
            new_transaction=new_transaction,
            read_time=read_time)
        return self._run_query(request, options)

    def write(self, requests, options=None):
        """
        Streams batches of document updates and deletes, in order.

        EXPERIMENTAL: This method interface might change in the future.

        Example:
            >>> from google.cloud import firestore_v1beta1
            >>>
            >>> client = firestore_v1beta1.FirestoreClient()
            >>>
            >>> database = client.database_root_path('[PROJECT]', '[DATABASE]')
            >>> request = {'database': database}
            >>>
            >>> requests = [request]
            >>> for element in client.write(requests):
            ...     # process element
            ...     pass

        Args:
            requests (iterator[dict|google.cloud.firestore_v1beta1.proto.firestore_pb2.WriteRequest]): The input objects. If a dict is provided, it must be of the
                same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.WriteRequest`
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            Iterable[~google.cloud.firestore_v1beta1.types.WriteResponse].

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        return self._write(requests, options)

    def listen(self, requests, options=None):
        """
        Listens to changes.

        EXPERIMENTAL: This method interface might change in the future.

        Example:
            >>> from google.cloud import firestore_v1beta1
            >>>
            >>> client = firestore_v1beta1.FirestoreClient()
            >>>
            >>> database = client.database_root_path('[PROJECT]', '[DATABASE]')
            >>> request = {'database': database}
            >>>
            >>> requests = [request]
            >>> for element in client.listen(requests):
            ...     # process element
            ...     pass

        Args:
            requests (iterator[dict|google.cloud.firestore_v1beta1.proto.firestore_pb2.ListenRequest]): The input objects. If a dict is provided, it must be of the
                same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.ListenRequest`
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            Iterable[~google.cloud.firestore_v1beta1.types.ListenResponse].

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        return self._listen(requests, options)

    def list_collection_ids(self, parent, page_size=None, options=None):
        """
        Lists all the collection IDs underneath a document.

        Example:
            >>> from google.cloud import firestore_v1beta1
            >>> from google.gax import CallOptions, INITIAL_PAGE
            >>>
            >>> client = firestore_v1beta1.FirestoreClient()
            >>>
            >>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
            >>>
            >>>
            >>> # Iterate over all results
            >>> for element in client.list_collection_ids(parent):
            ...     # process element
            ...     pass
            >>>
            >>> # Or iterate over results one page at a time
            >>> for page in client.list_collection_ids(parent, options=CallOptions(page_token=INITIAL_PAGE)):
            ...     for element in page:
            ...         # process element
            ...         pass

        Args:
            parent (str): The parent document. In the format:
                ``projects/{project_id}/databases/{database_id}/documents/{document_path}``.
                For example:
                ``projects/my-project/databases/my-database/documents/chatrooms/my-chatroom``
            page_size (int): The maximum number of resources contained in the
                underlying API response. If page streaming is performed per-
                resource, this parameter does not affect the return value. If page
                streaming is performed per-page, this determines the maximum number
                of resources in a page.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.gax.PageIterator` instance. By default, this
            is an iterable of :class:`str` instances.
            This object can also be configured to iterate over the pages
            of the response through the `options` parameter.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = firestore_pb2.ListCollectionIdsRequest(parent=parent,
                                                         page_size=page_size)
        return self._list_collection_ids(request, options)
Exemple #7
0
class PublisherApi(object):
    """
    The service that an application uses to manipulate topics, and to send
    messages to a topic.
    """

    SERVICE_ADDRESS = 'pubsub.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _CODE_GEN_NAME_VERSION = 'gapic/0.1.0'

    _GAX_VERSION = pkg_resources.get_distribution('google-gax').version

    _PAGE_DESCRIPTORS = {
        'list_topics':
        _PageDesc('page_token', 'next_page_token', 'topics'),
        'list_topic_subscriptions':
        _PageDesc('page_token', 'next_page_token', 'subscriptions')
    }

    _BUNDLE_DESCRIPTORS = {
        'publish':
        _BundleDesc(
            'messages',
            ['topic'],
            subresponse_field='message_ids',
        )
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = (
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/pubsub',
    )

    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')
    _TOPIC_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/topics/{topic}')

    @classmethod
    def project_path(cls, project):
        """Returns a fully-qualified project resource name string."""
        return cls._PROJECT_PATH_TEMPLATE.render({
            'project': project,
        })

    @classmethod
    def topic_path(cls, project, topic):
        """Returns a fully-qualified topic resource name string."""
        return cls._TOPIC_PATH_TEMPLATE.render({
            'project': project,
            'topic': topic,
        })

    @classmethod
    def match_project_from_project_name(cls, project_name):
        """Parses the project from a project resource.

        Args:
          project_name (string): A fully-qualified path representing a project
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')

    @classmethod
    def match_project_from_topic_name(cls, topic_name):
        """Parses the project from a topic resource.

        Args:
          topic_name (string): A fully-qualified path representing a topic
            resource.

        Returns:
          A string representing the project.
        """
        return cls._TOPIC_PATH_TEMPLATE.match(topic_name).get('project')

    @classmethod
    def match_topic_from_topic_name(cls, topic_name):
        """Parses the topic from a topic resource.

        Args:
          topic_name (string): A fully-qualified path representing a topic
            resource.

        Returns:
          A string representing the topic.
        """
        return cls._TOPIC_PATH_TEMPLATE.match(topic_name).get('topic')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 metadata_transformer=None,
                 ssl_creds=None,
                 scopes=None,
                 client_config=None,
                 app_name='gax',
                 app_version=_GAX_VERSION):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          ssl_creds (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          metadata_transformer (Callable[[], list]): A function that creates
             the metadata for requests.
          app_name (string): The codename of the calling service.
          app_version (string): The version of the calling service.

        Returns:
          A PublisherApi object.
        """
        if scopes is None:
            scopes = self._ALL_SCOPES
        if client_config is None:
            client_config = {}
        goog_api_client = '{}/{} {} gax/{} python/{}'.format(
            app_name, app_version, self._CODE_GEN_NAME_VERSION,
            self._GAX_VERSION, platform.python_version())
        metadata = [('x-goog-api-client', goog_api_client)]
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'publisher_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.pubsub.v1.Publisher',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            kwargs={'metadata': metadata},
            bundle_descriptors=self._BUNDLE_DESCRIPTORS,
            page_descriptors=self._PAGE_DESCRIPTORS)
        self.stub = config.create_stub(
            pubsub_pb2.PublisherStub,
            service_path,
            port,
            ssl_creds=ssl_creds,
            channel=channel,
            metadata_transformer=metadata_transformer,
            scopes=scopes)
        self._create_topic = api_callable.create_api_call(
            self.stub.CreateTopic, settings=defaults['create_topic'])
        self._publish = api_callable.create_api_call(
            self.stub.Publish, settings=defaults['publish'])
        self._get_topic = api_callable.create_api_call(
            self.stub.GetTopic, settings=defaults['get_topic'])
        self._list_topics = api_callable.create_api_call(
            self.stub.ListTopics, settings=defaults['list_topics'])
        self._list_topic_subscriptions = api_callable.create_api_call(
            self.stub.ListTopicSubscriptions,
            settings=defaults['list_topic_subscriptions'])
        self._delete_topic = api_callable.create_api_call(
            self.stub.DeleteTopic, settings=defaults['delete_topic'])

    # Service calls
    def create_topic(self, name, options=None):
        """
        Creates the given topic with the given name.

        Example:
          >>> from google.cloud.gapic.pubsub.v1.publisher_api import PublisherApi
          >>> api = PublisherApi()
          >>> name = api.topic_path('[PROJECT]', '[TOPIC]')
          >>> response = api.create_topic(name)

        Args:
          name (string): The name of the topic. It must have the format
            ``\"projects/{project}/topics/{topic}\"``. ``{topic}`` must start with a letter,
            and contain only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes (``-``),
            underscores (``_``), periods (``.``), tildes (``~``), plus (``+``) or percent
            signs (``%``). It must be between 3 and 255 characters in length, and it
            must not start with ``\"goog\"``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.pubsub.v1.pubsub_pb2.Topic` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
        """
        request = pubsub_pb2.Topic(name=name)
        return self._create_topic(request, options)

    def publish(self, topic, messages, options=None):
        """
        Adds one or more messages to the topic. Returns ``NOT_FOUND`` if the topic
        does not exist. The message payload must not be empty; it must contain
        either a non-empty data field, or at least one attribute.

        Example:
          >>> from google.cloud.gapic.pubsub.v1.publisher_api import PublisherApi
          >>> from google.pubsub.v1 import pubsub_pb2
          >>> api = PublisherApi()
          >>> topic = api.topic_path('[PROJECT]', '[TOPIC]')
          >>> data = ''
          >>> messages_element = pubsub_pb2.PubsubMessage(data)
          >>> messages = [messages_element]
          >>> response = api.publish(topic, messages)

        Args:
          topic (string): The messages in the request will be published on this topic.
          messages (list[:class:`google.pubsub.v1.pubsub_pb2.PubsubMessage`]): The messages to publish.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.pubsub.v1.pubsub_pb2.PublishResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
        """
        request = pubsub_pb2.PublishRequest(topic=topic, messages=messages)
        return self._publish(request, options)

    def get_topic(self, topic, options=None):
        """
        Gets the configuration of a topic.

        Example:
          >>> from google.cloud.gapic.pubsub.v1.publisher_api import PublisherApi
          >>> api = PublisherApi()
          >>> topic = api.topic_path('[PROJECT]', '[TOPIC]')
          >>> response = api.get_topic(topic)

        Args:
          topic (string): The name of the topic to get.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.pubsub.v1.pubsub_pb2.Topic` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
        """
        request = pubsub_pb2.GetTopicRequest(topic=topic)
        return self._get_topic(request, options)

    def list_topics(self, project, page_size=0, options=None):
        """
        Lists matching topics.

        Example:
          >>> from google.cloud.gapic.pubsub.v1.publisher_api import PublisherApi
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = PublisherApi()
          >>> project = api.project_path('[PROJECT]')
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_topics(project):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_topics(project, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          project (string): The name of the cloud project that topics belong to.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.pubsub.v1.pubsub_pb2.Topic` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
        """
        request = pubsub_pb2.ListTopicsRequest(project=project,
                                               page_size=page_size)
        return self._list_topics(request, options)

    def list_topic_subscriptions(self, topic, page_size=0, options=None):
        """
        Lists the name of the subscriptions for this topic.

        Example:
          >>> from google.cloud.gapic.pubsub.v1.publisher_api import PublisherApi
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = PublisherApi()
          >>> topic = api.topic_path('[PROJECT]', '[TOPIC]')
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_topic_subscriptions(topic):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_topic_subscriptions(topic, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          topic (string): The name of the topic that subscriptions are attached to.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of string instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
        """
        request = pubsub_pb2.ListTopicSubscriptionsRequest(topic=topic,
                                                           page_size=page_size)
        return self._list_topic_subscriptions(request, options)

    def delete_topic(self, topic, options=None):
        """
        Deletes the topic with the given name. Returns ``NOT_FOUND`` if the topic
        does not exist. After a topic is deleted, a new topic may be created with
        the same name; this is an entirely new topic with none of the old
        configuration or subscriptions. Existing subscriptions to this topic are
        not deleted, but their ``topic`` field is set to ``_deleted-topic_``.

        Example:
          >>> from google.cloud.gapic.pubsub.v1.publisher_api import PublisherApi
          >>> api = PublisherApi()
          >>> topic = api.topic_path('[PROJECT]', '[TOPIC]')
          >>> api.delete_topic(topic)

        Args:
          topic (string): Name of the topic to delete.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
        """
        request = pubsub_pb2.DeleteTopicRequest(topic=topic)
        self._delete_topic(request, options)
class SubscriberApi(object):
    """
    The service that an application uses to manipulate subscriptions and to
    consume messages from a subscription via the ``Pull`` method.
    """

    SERVICE_ADDRESS = 'pubsub.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _CODE_GEN_NAME_VERSION = 'gapic/0.1.0'

    _GAX_VERSION = pkg_resources.get_distribution('google-gax').version

    _PAGE_DESCRIPTORS = {
        'list_subscriptions':
        _PageDesc('page_token', 'next_page_token', 'subscriptions')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = (
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/pubsub',
    )

    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')
    _SUBSCRIPTION_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/subscriptions/{subscription}')
    _TOPIC_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/topics/{topic}')

    @classmethod
    def project_path(cls, project):
        """Returns a fully-qualified project resource name string."""
        return cls._PROJECT_PATH_TEMPLATE.render({
            'project': project,
        })

    @classmethod
    def subscription_path(cls, project, subscription):
        """Returns a fully-qualified subscription resource name string."""
        return cls._SUBSCRIPTION_PATH_TEMPLATE.render({
            'project':
            project,
            'subscription':
            subscription,
        })

    @classmethod
    def topic_path(cls, project, topic):
        """Returns a fully-qualified topic resource name string."""
        return cls._TOPIC_PATH_TEMPLATE.render({
            'project': project,
            'topic': topic,
        })

    @classmethod
    def match_project_from_project_name(cls, project_name):
        """Parses the project from a project resource.

        Args:
          project_name (string): A fully-qualified path representing a project
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')

    @classmethod
    def match_project_from_subscription_name(cls, subscription_name):
        """Parses the project from a subscription resource.

        Args:
          subscription_name (string): A fully-qualified path representing a subscription
            resource.

        Returns:
          A string representing the project.
        """
        return cls._SUBSCRIPTION_PATH_TEMPLATE.match(subscription_name).get(
            'project')

    @classmethod
    def match_subscription_from_subscription_name(cls, subscription_name):
        """Parses the subscription from a subscription resource.

        Args:
          subscription_name (string): A fully-qualified path representing a subscription
            resource.

        Returns:
          A string representing the subscription.
        """
        return cls._SUBSCRIPTION_PATH_TEMPLATE.match(subscription_name).get(
            'subscription')

    @classmethod
    def match_project_from_topic_name(cls, topic_name):
        """Parses the project from a topic resource.

        Args:
          topic_name (string): A fully-qualified path representing a topic
            resource.

        Returns:
          A string representing the project.
        """
        return cls._TOPIC_PATH_TEMPLATE.match(topic_name).get('project')

    @classmethod
    def match_topic_from_topic_name(cls, topic_name):
        """Parses the topic from a topic resource.

        Args:
          topic_name (string): A fully-qualified path representing a topic
            resource.

        Returns:
          A string representing the topic.
        """
        return cls._TOPIC_PATH_TEMPLATE.match(topic_name).get('topic')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 metadata_transformer=None,
                 ssl_creds=None,
                 scopes=None,
                 client_config=None,
                 app_name='gax',
                 app_version=_GAX_VERSION):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          ssl_creds (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          metadata_transformer (Callable[[], list]): A function that creates
             the metadata for requests.
          app_name (string): The codename of the calling service.
          app_version (string): The version of the calling service.

        Returns:
          A SubscriberApi object.
        """
        if scopes is None:
            scopes = self._ALL_SCOPES
        if client_config is None:
            client_config = {}
        goog_api_client = '{}/{} {} gax/{} python/{}'.format(
            app_name, app_version, self._CODE_GEN_NAME_VERSION,
            self._GAX_VERSION, platform.python_version())
        metadata = [('x-goog-api-client', goog_api_client)]
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'subscriber_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.pubsub.v1.Subscriber',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            kwargs={'metadata': metadata},
            page_descriptors=self._PAGE_DESCRIPTORS)
        self.iam_policy_stub = config.create_stub(
            iam_policy_pb2.IAMPolicyStub,
            service_path,
            port,
            ssl_creds=ssl_creds,
            channel=channel,
            metadata_transformer=metadata_transformer,
            scopes=scopes)
        self.subscriber_stub = config.create_stub(
            pubsub_pb2.SubscriberStub,
            service_path,
            port,
            ssl_creds=ssl_creds,
            channel=channel,
            metadata_transformer=metadata_transformer,
            scopes=scopes)

        self._create_subscription = api_callable.create_api_call(
            self.subscriber_stub.CreateSubscription,
            settings=defaults['create_subscription'])
        self._get_subscription = api_callable.create_api_call(
            self.subscriber_stub.GetSubscription,
            settings=defaults['get_subscription'])
        self._list_subscriptions = api_callable.create_api_call(
            self.subscriber_stub.ListSubscriptions,
            settings=defaults['list_subscriptions'])
        self._delete_subscription = api_callable.create_api_call(
            self.subscriber_stub.DeleteSubscription,
            settings=defaults['delete_subscription'])
        self._modify_ack_deadline = api_callable.create_api_call(
            self.subscriber_stub.ModifyAckDeadline,
            settings=defaults['modify_ack_deadline'])
        self._acknowledge = api_callable.create_api_call(
            self.subscriber_stub.Acknowledge, settings=defaults['acknowledge'])
        self._pull = api_callable.create_api_call(self.subscriber_stub.Pull,
                                                  settings=defaults['pull'])
        self._modify_push_config = api_callable.create_api_call(
            self.subscriber_stub.ModifyPushConfig,
            settings=defaults['modify_push_config'])
        self._set_iam_policy = api_callable.create_api_call(
            self.iam_policy_stub.SetIamPolicy,
            settings=defaults['set_iam_policy'])
        self._get_iam_policy = api_callable.create_api_call(
            self.iam_policy_stub.GetIamPolicy,
            settings=defaults['get_iam_policy'])
        self._test_iam_permissions = api_callable.create_api_call(
            self.iam_policy_stub.TestIamPermissions,
            settings=defaults['test_iam_permissions'])

    # Service calls
    def create_subscription(self,
                            name,
                            topic,
                            push_config=None,
                            ack_deadline_seconds=0,
                            options=None):
        """
        Creates a subscription to a given topic.
        If the subscription already exists, returns ``ALREADY_EXISTS``.
        If the corresponding topic doesn't exist, returns ``NOT_FOUND``.
        If the name is not provided in the request, the server will assign a random
        name for this subscription on the same project as the topic. Note that
        for REST API requests, you must specify a name.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_api
          >>> api = subscriber_api.SubscriberApi()
          >>> name = api.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> topic = api.topic_path('[PROJECT]', '[TOPIC]')
          >>> response = api.create_subscription(name, topic)

        Args:
          name (string): The name of the subscription. It must have the format
            ``\"projects/{project}/subscriptions/{subscription}\"``. ``{subscription}`` must
            start with a letter, and contain only letters (``[A-Za-z]``), numbers
            (``[0-9]``), dashes (``-``), underscores (``_``), periods (``.``), tildes (``~``),
            plus (``+``) or percent signs (``%``). It must be between 3 and 255 characters
            in length, and it must not start with ``\"goog\"``.
          topic (string): The name of the topic from which this subscription is receiving messages.
            The value of this field will be ``_deleted-topic_`` if the topic has been
            deleted.
          push_config (:class:`google.pubsub.v1.pubsub_pb2.PushConfig`): If push delivery is used with this subscription, this field is
            used to configure it. An empty ``pushConfig`` signifies that the subscriber
            will pull and ack messages using API methods.
          ack_deadline_seconds (int): This value is the maximum time after a subscriber receives a message
            before the subscriber should acknowledge the message. After message
            delivery but before the ack deadline expires and before the message is
            acknowledged, it is an outstanding message and will not be delivered
            again during that time (on a best-effort basis).

            For pull subscriptions, this value is used as the initial value for the ack
            deadline. To override this value for a given message, call
            ``ModifyAckDeadline`` with the corresponding ``ack_id`` if using
            pull.
            The maximum custom deadline you can specify is 600 seconds (10 minutes).

            For push delivery, this value is also used to set the request timeout for
            the call to the push endpoint.

            If the subscriber never acknowledges the message, the Pub/Sub
            system will eventually redeliver the message.

            If this parameter is 0, a default value of 10 seconds is used.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.pubsub.v1.pubsub_pb2.Subscription` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        if push_config is None:
            push_config = pubsub_pb2.PushConfig()
        request = pubsub_pb2.Subscription(
            name=name,
            topic=topic,
            push_config=push_config,
            ack_deadline_seconds=ack_deadline_seconds)
        return self._create_subscription(request, options)

    def get_subscription(self, subscription, options=None):
        """
        Gets the configuration details of a subscription.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_api
          >>> api = subscriber_api.SubscriberApi()
          >>> subscription = api.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> response = api.get_subscription(subscription)

        Args:
          subscription (string): The name of the subscription to get.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.pubsub.v1.pubsub_pb2.Subscription` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = pubsub_pb2.GetSubscriptionRequest(subscription=subscription)
        return self._get_subscription(request, options)

    def list_subscriptions(self, project, page_size=0, options=None):
        """
        Lists matching subscriptions.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_api
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = subscriber_api.SubscriberApi()
          >>> project = api.project_path('[PROJECT]')
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_subscriptions(project):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_subscriptions(project, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          project (string): The name of the cloud project that subscriptions belong to.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.pubsub.v1.pubsub_pb2.Subscription` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = pubsub_pb2.ListSubscriptionsRequest(project=project,
                                                      page_size=page_size)
        return self._list_subscriptions(request, options)

    def delete_subscription(self, subscription, options=None):
        """
        Deletes an existing subscription. All pending messages in the subscription
        are immediately dropped. Calls to ``Pull`` after deletion will return
        ``NOT_FOUND``. After a subscription is deleted, a new one may be created with
        the same name, but the new one has no association with the old
        subscription, or its topic unless the same topic is specified.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_api
          >>> api = subscriber_api.SubscriberApi()
          >>> subscription = api.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> api.delete_subscription(subscription)

        Args:
          subscription (string): The subscription to delete.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = pubsub_pb2.DeleteSubscriptionRequest(
            subscription=subscription)
        self._delete_subscription(request, options)

    def modify_ack_deadline(self,
                            subscription,
                            ack_ids,
                            ack_deadline_seconds,
                            options=None):
        """
        Modifies the ack deadline for a specific message. This method is useful
        to indicate that more time is needed to process a message by the
        subscriber, or to make the message available for redelivery if the
        processing was interrupted. Note that this does not modify the
        subscription-level ``ackDeadlineSeconds`` used for subsequent messages.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_api
          >>> api = subscriber_api.SubscriberApi()
          >>> subscription = api.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> ack_ids = []
          >>> ack_deadline_seconds = 0
          >>> api.modify_ack_deadline(subscription, ack_ids, ack_deadline_seconds)

        Args:
          subscription (string): The name of the subscription.
          ack_ids (list[string]): List of acknowledgment IDs.
          ack_deadline_seconds (int): The new ack deadline with respect to the time this request was sent to
            the Pub/Sub system. Must be >= 0. For example, if the value is 10, the new
            ack deadline will expire 10 seconds after the ``ModifyAckDeadline`` call
            was made. Specifying zero may immediately make the message available for
            another pull request.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = pubsub_pb2.ModifyAckDeadlineRequest(
            subscription=subscription,
            ack_ids=ack_ids,
            ack_deadline_seconds=ack_deadline_seconds)
        self._modify_ack_deadline(request, options)

    def acknowledge(self, subscription, ack_ids, options=None):
        """
        Acknowledges the messages associated with the ``ack_ids`` in the
        ``AcknowledgeRequest``. The Pub/Sub system can remove the relevant messages
        from the subscription.
        Acknowledging a message whose ack deadline has expired may succeed,
        but such a message may be redelivered later. Acknowledging a message more
        than once will not result in an error.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_api
          >>> api = subscriber_api.SubscriberApi()
          >>> subscription = api.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> ack_ids = []
          >>> api.acknowledge(subscription, ack_ids)

        Args:
          subscription (string): The subscription whose message is being acknowledged.
          ack_ids (list[string]): The acknowledgment ID for the messages being acknowledged that was returned
            by the Pub/Sub system in the ``Pull`` response. Must not be empty.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = pubsub_pb2.AcknowledgeRequest(subscription=subscription,
                                                ack_ids=ack_ids)
        self._acknowledge(request, options)

    def pull(self,
             subscription,
             max_messages,
             return_immediately=False,
             options=None):
        """
        Pulls messages from the server. Returns an empty list if there are no
        messages available in the backlog. The server may return ``UNAVAILABLE`` if
        there are too many concurrent pull requests pending for the given
        subscription.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_api
          >>> api = subscriber_api.SubscriberApi()
          >>> subscription = api.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> max_messages = 0
          >>> response = api.pull(subscription, max_messages)

        Args:
          subscription (string): The subscription from which messages should be pulled.
          return_immediately (bool): If this is specified as true the system will respond immediately even if
            it is not able to return a message in the ``Pull`` response. Otherwise the
            system is allowed to wait until at least one message is available rather
            than returning no messages. The client may cancel the request if it does
            not wish to wait any longer for the response.
          max_messages (int): The maximum number of messages returned for this request. The Pub/Sub
            system may return fewer than the number specified.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.pubsub.v1.pubsub_pb2.PullResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = pubsub_pb2.PullRequest(subscription=subscription,
                                         max_messages=max_messages,
                                         return_immediately=return_immediately)
        return self._pull(request, options)

    def modify_push_config(self, subscription, push_config, options=None):
        """
        Modifies the ``PushConfig`` for a specified subscription.
        This may be used to change a push subscription to a pull one (signified by
        an empty ``PushConfig``) or vice versa, or change the endpoint URL and other
        attributes of a push subscription. Messages will accumulate for delivery
        continuously through the call regardless of changes to the ``PushConfig``.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_api
          >>> from google.pubsub.v1 import pubsub_pb2
          >>> api = subscriber_api.SubscriberApi()
          >>> subscription = api.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> push_config = pubsub_pb2.PushConfig()
          >>> api.modify_push_config(subscription, push_config)

        Args:
          subscription (string): The name of the subscription.
          push_config (:class:`google.pubsub.v1.pubsub_pb2.PushConfig`): The push configuration for future deliveries.

            An empty ``pushConfig`` indicates that the Pub/Sub system should
            stop pushing messages from the given subscription and allow
            messages to be pulled and acknowledged - effectively pausing
            the subscription if ``Pull`` is not called.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = pubsub_pb2.ModifyPushConfigRequest(subscription=subscription,
                                                     push_config=push_config)
        self._modify_push_config(request, options)

    def set_iam_policy(self, resource, policy, options=None):
        """
        Sets the access control policy on the specified resource. Replaces any
        existing policy.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_api
          >>> from google.iam.v1 import policy_pb2
          >>> api = subscriber_api.SubscriberApi()
          >>> resource = api.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> policy = policy_pb2.Policy()
          >>> response = api.set_iam_policy(resource, policy)

        Args:
          resource (string): REQUIRED: The resource for which policy is being specified.
            Resource is usually specified as a path, such as,
            projects/{project}/zones/{zone}/disks/{disk}.
          policy (:class:`google.iam.v1.policy_pb2.Policy`): REQUIRED: The complete policy to be applied to the 'resource'. The size of
            the policy is limited to a few 10s of KB. An empty policy is in general a
            valid policy but certain services (like Projects) might reject them.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.v1.policy_pb2.Policy` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_policy_pb2.SetIamPolicyRequest(resource=resource,
                                                     policy=policy)
        return self._set_iam_policy(request, options)

    def get_iam_policy(self, resource, options=None):
        """
        Gets the access control policy for a resource. Is empty if the
        policy or the resource does not exist.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_api
          >>> api = subscriber_api.SubscriberApi()
          >>> resource = api.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> response = api.get_iam_policy(resource)

        Args:
          resource (string): REQUIRED: The resource for which policy is being requested. Resource
            is usually specified as a path, such as, projects/{project}.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.v1.policy_pb2.Policy` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_policy_pb2.GetIamPolicyRequest(resource=resource)
        return self._get_iam_policy(request, options)

    def test_iam_permissions(self, resource, permissions, options=None):
        """
        Returns permissions that a caller has on the specified resource.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_api
          >>> api = subscriber_api.SubscriberApi()
          >>> resource = api.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> permissions = []
          >>> response = api.test_iam_permissions(resource, permissions)

        Args:
          resource (string): REQUIRED: The resource for which policy detail is being requested.
            Resource is usually specified as a path, such as, projects/{project}.
          permissions (list[string]): The set of permissions to check for the 'resource'. Permissions with
            wildcards (such as '*' or 'storage.*') are not allowed.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_policy_pb2.TestIamPermissionsRequest(
            resource=resource, permissions=permissions)
        return self._test_iam_permissions(request, options)
class ReportErrorsServiceApi(object):
    """An API for reporting error events."""

    SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _CODE_GEN_NAME_VERSION = 'gapic/0.1.0'

    _GAX_VERSION = pkg_resources.get_distribution('google-gax').version

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = ('https://www.googleapis.com/auth/cloud-platform', )

    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')

    @classmethod
    def project_path(cls, project):
        """Returns a fully-qualified project resource name string."""
        return cls._PROJECT_PATH_TEMPLATE.render({
            'project': project,
        })

    @classmethod
    def match_project_from_project_name(cls, project_name):
        """Parses the project from a project resource.

        Args:
          project_name (string): A fully-qualified path representing a project
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 metadata_transformer=None,
                 ssl_creds=None,
                 scopes=None,
                 client_config=None,
                 app_name='gax',
                 app_version=_GAX_VERSION):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          ssl_creds (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          metadata_transformer (Callable[[], list]): A function that creates
             the metadata for requests.
          app_name (string): The codename of the calling service.
          app_version (string): The version of the calling service.

        Returns:
          A ReportErrorsServiceApi object.
        """
        if scopes is None:
            scopes = self._ALL_SCOPES
        if client_config is None:
            client_config = {}
        goog_api_client = '{}/{} {} gax/{} python/{}'.format(
            app_name, app_version, self._CODE_GEN_NAME_VERSION,
            self._GAX_VERSION, platform.python_version())
        metadata = [('x-goog-api-client', goog_api_client)]
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'report_errors_service_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.devtools.clouderrorreporting.v1beta1.ReportErrorsService',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            kwargs={'metadata': metadata})
        self.report_errors_service_stub = config.create_stub(
            report_errors_service_pb2.ReportErrorsServiceStub,
            service_path,
            port,
            ssl_creds=ssl_creds,
            channel=channel,
            metadata_transformer=metadata_transformer,
            scopes=scopes)

        self._report_error_event = api_callable.create_api_call(
            self.report_errors_service_stub.ReportErrorEvent,
            settings=defaults['report_error_event'])

    # Service calls
    def report_error_event(self, project_name, event, options=None):
        """
        Report an individual error event.
        This endpoint accepts <strong>either</strong> an OAuth token,
        <strong>or</strong> an
        <a href=\"https://support.google.com/cloud/answer/6158862\">API key</a>
        for authentication. To use an API key, append it to the URL as the value of
        a ``key`` parameter. For example:
        <pre>POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456</pre>

        Example:
          >>> from google.cloud.gapic.errorreporting.v1beta1 import report_errors_service_api
          >>> from google.devtools.clouderrorreporting.v1beta1 import report_errors_service_pb2
          >>> api = report_errors_service_api.ReportErrorsServiceApi()
          >>> project_name = api.project_path('[PROJECT]')
          >>> event = report_errors_service_pb2.ReportedErrorEvent()
          >>> response = api.report_error_event(project_name, event)

        Args:
          project_name (string): [Required] The resource name of the Google Cloud Platform project. Written
            as ``projects/`` plus the
            `Google Cloud Platform project ID <https://support.google.com/cloud/answer/6158840>`_.
            Example: ``projects/my-project-123``.
          event (:class:`google.devtools.clouderrorreporting.v1beta1.report_errors_service_pb2.ReportedErrorEvent`): [Required] The error event to be reported.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = report_errors_service_pb2.ReportErrorEventRequest(
            project_name=project_name, event=event)
        self._report_error_event(request, options)
class InstanceAdminClient(object):
    """
    Cloud Spanner Instance Admin API

    The Cloud Spanner Instance Admin API can be used to create, delete,
    modify and list instances. Instances are dedicated Cloud Spanner serving
    and storage resources to be used by Cloud Spanner databases.

    Each instance has a \"configuration\", which dictates where the
    serving resources for the Cloud Spanner instance are located (e.g.,
    US-central, Europe). Configurations are created by Google based on
    resource availability.

    Cloud Spanner billing is based on the instances that exist and their
    sizes. After an instance exists, there are no additional
    per-database or per-operation charges for use of the instance
    (though there may be additional network bandwidth charges).
    Instances offer isolation: problems with databases in one instance
    will not affect other instances. However, within an instance
    databases can affect each other. For example, if one database in an
    instance receives a lot of requests and consumes most of the
    instance resources, fewer resources are available for other
    databases in that instance, and their performance may suffer.
    """

    SERVICE_ADDRESS = 'spanner.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _PAGE_DESCRIPTORS = {
        'list_instance_configs':
        _PageDesc('page_token', 'next_page_token', 'instance_configs'),
        'list_instances':
        _PageDesc('page_token', 'next_page_token', 'instances')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = (
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/spanner.admin',
    )

    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')
    _INSTANCE_CONFIG_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/instanceConfigs/{instance_config}')
    _INSTANCE_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/instances/{instance}')

    @classmethod
    def project_path(cls, project):
        """Returns a fully-qualified project resource name string."""
        return cls._PROJECT_PATH_TEMPLATE.render({
            'project': project,
        })

    @classmethod
    def instance_config_path(cls, project, instance_config):
        """Returns a fully-qualified instance_config resource name string."""
        return cls._INSTANCE_CONFIG_PATH_TEMPLATE.render({
            'project':
            project,
            'instance_config':
            instance_config,
        })

    @classmethod
    def instance_path(cls, project, instance):
        """Returns a fully-qualified instance resource name string."""
        return cls._INSTANCE_PATH_TEMPLATE.render({
            'project': project,
            'instance': instance,
        })

    @classmethod
    def match_project_from_project_name(cls, project_name):
        """Parses the project from a project resource.

        Args:
            project_name (str): A fully-qualified path representing a project
                resource.

        Returns:
            A string representing the project.
        """
        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')

    @classmethod
    def match_project_from_instance_config_name(cls, instance_config_name):
        """Parses the project from a instance_config resource.

        Args:
            instance_config_name (str): A fully-qualified path representing a instance_config
                resource.

        Returns:
            A string representing the project.
        """
        return cls._INSTANCE_CONFIG_PATH_TEMPLATE.match(
            instance_config_name).get('project')

    @classmethod
    def match_instance_config_from_instance_config_name(
            cls, instance_config_name):
        """Parses the instance_config from a instance_config resource.

        Args:
            instance_config_name (str): A fully-qualified path representing a instance_config
                resource.

        Returns:
            A string representing the instance_config.
        """
        return cls._INSTANCE_CONFIG_PATH_TEMPLATE.match(
            instance_config_name).get('instance_config')

    @classmethod
    def match_project_from_instance_name(cls, instance_name):
        """Parses the project from a instance resource.

        Args:
            instance_name (str): A fully-qualified path representing a instance
                resource.

        Returns:
            A string representing the project.
        """
        return cls._INSTANCE_PATH_TEMPLATE.match(instance_name).get('project')

    @classmethod
    def match_instance_from_instance_name(cls, instance_name):
        """Parses the instance from a instance resource.

        Args:
            instance_name (str): A fully-qualified path representing a instance
                resource.

        Returns:
            A string representing the instance.
        """
        return cls._INSTANCE_PATH_TEMPLATE.match(instance_name).get('instance')

    def __init__(self,
                 channel=None,
                 credentials=None,
                 ssl_credentials=None,
                 scopes=None,
                 client_config=None,
                 lib_name=None,
                 lib_version='',
                 metrics_headers=()):
        """Constructor.

        Args:
            channel (~grpc.Channel): A ``Channel`` instance through
                which to make calls.
            credentials (~google.auth.credentials.Credentials): The authorization
                credentials to attach to requests. These credentials identify this
                application to the service.
            ssl_credentials (~grpc.ChannelCredentials): A
                ``ChannelCredentials`` instance for use with an SSL-enabled
                channel.
            scopes (Sequence[str]): A list of OAuth2 scopes to attach to requests.
            client_config (dict):
                A dictionary for call options for each method. See
                :func:`google.gax.construct_settings` for the structure of
                this data. Falls back to the default config if not specified
                or the specified config is missing data points.
            lib_name (str): The API library software used for calling
                the service. (Unless you are writing an API client itself,
                leave this as default.)
            lib_version (str): The API library software version used
                for calling the service. (Unless you are writing an API client
                itself, leave this as default.)
            metrics_headers (dict): A dictionary of values for tracking
                client library metrics. Ultimately serializes to a string
                (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be
                considered private.
        """
        # Unless the calling application specifically requested
        # OAuth scopes, request everything.
        if scopes is None:
            scopes = self._ALL_SCOPES

        # Initialize an empty client config, if none is set.
        if client_config is None:
            client_config = {}

        # Initialize metrics_headers as an ordered dictionary
        # (cuts down on cardinality of the resulting string slightly).
        metrics_headers = collections.OrderedDict(metrics_headers)
        metrics_headers['gl-python'] = platform.python_version()

        # The library may or may not be set, depending on what is
        # calling this client. Newer client libraries set the library name
        # and version.
        if lib_name:
            metrics_headers[lib_name] = lib_version

        # Finally, track the GAPIC package version.
        metrics_headers['gapic'] = pkg_resources.get_distribution(
            'google-cloud-spanner', ).version

        # Load the configuration defaults.
        defaults = api_callable.construct_settings(
            'google.spanner.admin.instance.v1.InstanceAdmin',
            instance_admin_client_config.config,
            client_config,
            config.STATUS_CODE_NAMES,
            metrics_headers=metrics_headers,
            page_descriptors=self._PAGE_DESCRIPTORS,
        )
        self.instance_admin_stub = config.create_stub(
            spanner_instance_admin_pb2.InstanceAdminStub,
            channel=channel,
            service_path=self.SERVICE_ADDRESS,
            service_port=self.DEFAULT_SERVICE_PORT,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)

        self.operations_client = operations_client.OperationsClient(
            service_path=self.SERVICE_ADDRESS,
            channel=channel,
            credentials=credentials,
            ssl_credentials=ssl_credentials,
            scopes=scopes,
            client_config=client_config,
            metrics_headers=metrics_headers,
        )

        self._list_instance_configs = api_callable.create_api_call(
            self.instance_admin_stub.ListInstanceConfigs,
            settings=defaults['list_instance_configs'])
        self._get_instance_config = api_callable.create_api_call(
            self.instance_admin_stub.GetInstanceConfig,
            settings=defaults['get_instance_config'])
        self._list_instances = api_callable.create_api_call(
            self.instance_admin_stub.ListInstances,
            settings=defaults['list_instances'])
        self._get_instance = api_callable.create_api_call(
            self.instance_admin_stub.GetInstance,
            settings=defaults['get_instance'])
        self._create_instance = api_callable.create_api_call(
            self.instance_admin_stub.CreateInstance,
            settings=defaults['create_instance'])
        self._update_instance = api_callable.create_api_call(
            self.instance_admin_stub.UpdateInstance,
            settings=defaults['update_instance'])
        self._delete_instance = api_callable.create_api_call(
            self.instance_admin_stub.DeleteInstance,
            settings=defaults['delete_instance'])
        self._set_iam_policy = api_callable.create_api_call(
            self.instance_admin_stub.SetIamPolicy,
            settings=defaults['set_iam_policy'])
        self._get_iam_policy = api_callable.create_api_call(
            self.instance_admin_stub.GetIamPolicy,
            settings=defaults['get_iam_policy'])
        self._test_iam_permissions = api_callable.create_api_call(
            self.instance_admin_stub.TestIamPermissions,
            settings=defaults['test_iam_permissions'])

    # Service calls
    def list_instance_configs(self, parent, page_size=None, options=None):
        """
        Lists the supported instance configurations for a given project.

        Example:
            >>> from google.cloud import spanner_admin_instance_v1
            >>> from google.gax import CallOptions, INITIAL_PAGE
            >>>
            >>> client = spanner_admin_instance_v1.InstanceAdminClient()
            >>>
            >>> parent = client.project_path('[PROJECT]')
            >>>
            >>>
            >>> # Iterate over all results
            >>> for element in client.list_instance_configs(parent):
            ...     # process element
            ...     pass
            >>>
            >>> # Or iterate over results one page at a time
            >>> for page in client.list_instance_configs(parent, options=CallOptions(page_token=INITIAL_PAGE)):
            ...     for element in page:
            ...         # process element
            ...         pass

        Args:
            parent (str): Required. The name of the project for which a list of supported instance
                configurations is requested. Values are of the form
                ``projects/<project>``.
            page_size (int): The maximum number of resources contained in the
                underlying API response. If page streaming is performed per-
                resource, this parameter does not affect the return value. If page
                streaming is performed per-page, this determines the maximum number
                of resources in a page.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.gax.PageIterator` instance. By default, this
            is an iterable of :class:`~google.cloud.spanner_admin_instance_v1.types.InstanceConfig` instances.
            This object can also be configured to iterate over the pages
            of the response through the `options` parameter.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_instance_admin_pb2.ListInstanceConfigsRequest(
            parent=parent, page_size=page_size)
        return self._list_instance_configs(request, options)

    def get_instance_config(self, name, options=None):
        """
        Gets information about a particular instance configuration.

        Example:
            >>> from google.cloud import spanner_admin_instance_v1
            >>>
            >>> client = spanner_admin_instance_v1.InstanceAdminClient()
            >>>
            >>> name = client.instance_config_path('[PROJECT]', '[INSTANCE_CONFIG]')
            >>>
            >>> response = client.get_instance_config(name)

        Args:
            name (str): Required. The name of the requested instance configuration. Values are of
                the form ``projects/<project>/instanceConfigs/<config>``.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_admin_instance_v1.types.InstanceConfig` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_instance_admin_pb2.GetInstanceConfigRequest(
            name=name)
        return self._get_instance_config(request, options)

    def list_instances(self,
                       parent,
                       page_size=None,
                       filter_=None,
                       options=None):
        """
        Lists all instances in the given project.

        Example:
            >>> from google.cloud import spanner_admin_instance_v1
            >>> from google.gax import CallOptions, INITIAL_PAGE
            >>>
            >>> client = spanner_admin_instance_v1.InstanceAdminClient()
            >>>
            >>> parent = client.project_path('[PROJECT]')
            >>>
            >>>
            >>> # Iterate over all results
            >>> for element in client.list_instances(parent):
            ...     # process element
            ...     pass
            >>>
            >>> # Or iterate over results one page at a time
            >>> for page in client.list_instances(parent, options=CallOptions(page_token=INITIAL_PAGE)):
            ...     for element in page:
            ...         # process element
            ...         pass

        Args:
            parent (str): Required. The name of the project for which a list of instances is
                requested. Values are of the form ``projects/<project>``.
            page_size (int): The maximum number of resources contained in the
                underlying API response. If page streaming is performed per-
                resource, this parameter does not affect the return value. If page
                streaming is performed per-page, this determines the maximum number
                of resources in a page.
            filter_ (str): An expression for filtering the results of the request. Filter rules are
                case insensitive. The fields eligible for filtering are:

                  * name
                  * display_name
                  * labels.key where key is the name of a label

                Some examples of using filters are:

                  * name:* --> The instance has a name.
                  * name:Howl --> The instance's name contains the string \"howl\".
                  * name:HOWL --> Equivalent to above.
                  * NAME:howl --> Equivalent to above.
                  * labels.env:* --> The instance has the label \"env\".
                  * labels.env:dev --> The instance has the label \"env\" and the value of
                    the label contains the string \"dev\".
                  * name:howl labels.env:dev --> The instance's name contains \"howl\" and
                    it has the label \"env\" with its value containing \"dev\".

            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.gax.PageIterator` instance. By default, this
            is an iterable of :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` instances.
            This object can also be configured to iterate over the pages
            of the response through the `options` parameter.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_instance_admin_pb2.ListInstancesRequest(
            parent=parent, page_size=page_size, filter=filter_)
        return self._list_instances(request, options)

    def get_instance(self, name, options=None):
        """
        Gets information about a particular instance.

        Example:
            >>> from google.cloud import spanner_admin_instance_v1
            >>>
            >>> client = spanner_admin_instance_v1.InstanceAdminClient()
            >>>
            >>> name = client.instance_path('[PROJECT]', '[INSTANCE]')
            >>>
            >>> response = client.get_instance(name)

        Args:
            name (str): Required. The name of the requested instance. Values are of the form
                ``projects/<project>/instances/<instance>``.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_instance_admin_pb2.GetInstanceRequest(name=name)
        return self._get_instance(request, options)

    def create_instance(self, parent, instance_id, instance, options=None):
        """
        Creates an instance and begins preparing it to begin serving. The
        returned ``long-running operation``
        can be used to track the progress of preparing the new
        instance. The instance name is assigned by the caller. If the
        named instance already exists, ``CreateInstance`` returns
        ``ALREADY_EXISTS``.

        Immediately upon completion of this request:

        * The instance is readable via the API, with all requested attributes
          but no allocated resources. Its state is `CREATING`.

        Until completion of the returned operation:

        * Cancelling the operation renders the instance immediately unreadable
          via the API.
        * The instance can be deleted.
        * All other attempts to modify the instance are rejected.

        Upon completion of the returned operation:

        * Billing for all successfully-allocated resources begins (some types
          may have lower than the requested levels).
        * Databases can be created in the instance.
        * The instance's allocated resource levels are readable via the API.
        * The instance's state becomes ``READY``.

        The returned ``long-running operation`` will
        have a name of the format ``<instance_name>/operations/<operation_id>`` and
        can be used to track creation of the instance.  The
        ``metadata`` field type is
        ``CreateInstanceMetadata``.
        The ``response`` field type is
        ``Instance``, if successful.

        Example:
            >>> from google.cloud import spanner_admin_instance_v1
            >>>
            >>> client = spanner_admin_instance_v1.InstanceAdminClient()
            >>>
            >>> parent = client.project_path('[PROJECT]')
            >>> instance_id = ''
            >>> instance = {}
            >>>
            >>> response = client.create_instance(parent, instance_id, instance)
            >>>
            >>> def callback(operation_future):
            ...     # Handle result.
            ...     result = operation_future.result()
            >>>
            >>> response.add_done_callback(callback)
            >>>
            >>> # Handle metadata.
            >>> metadata = response.metadata()

        Args:
            parent (str): Required. The name of the project in which to create the instance. Values
                are of the form ``projects/<project>``.
            instance_id (str): Required. The ID of the instance to create.  Valid identifiers are of the
                form ``[a-z][-a-z0-9]*[a-z0-9]`` and must be between 6 and 30 characters in
                length.
            instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to create.  The name may be omitted, but if
                specified must be ``<parent>/instances/<instance_id>``.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance`
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_admin_instance_v1.types._OperationFuture` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_instance_admin_pb2.CreateInstanceRequest(
            parent=parent, instance_id=instance_id, instance=instance)
        return google.gax._OperationFuture(
            self._create_instance(request, options), self.operations_client,
            spanner_instance_admin_pb2.Instance,
            spanner_instance_admin_pb2.CreateInstanceMetadata, options)

    def update_instance(self, instance, field_mask, options=None):
        """
        Updates an instance, and begins allocating or releasing resources
        as requested. The returned [long-running
        operation][google.longrunning.Operation] can be used to track the
        progress of updating the instance. If the named instance does not
        exist, returns ``NOT_FOUND``.

        Immediately upon completion of this request:

        * For resource types for which a decrease in the instance's allocation
          has been requested, billing is based on the newly-requested level.

        Until completion of the returned operation:

        * Cancelling the operation sets its metadata's
          [cancel_time][google.spanner.admin.instance.v1.UpdateInstanceMetadata.cancel_time], and begins
          restoring resources to their pre-request values. The operation
          is guaranteed to succeed at undoing all resource changes,
          after which point it terminates with a `CANCELLED` status.
        * All other attempts to modify the instance are rejected.
        * Reading the instance via the API continues to give the pre-request
          resource levels.

        Upon completion of the returned operation:

        * Billing begins for all successfully-allocated resources (some types
          may have lower than the requested levels).
        * All newly-reserved resources are available for serving the instance's
          tables.
        * The instance's new resource levels are readable via the API.

        The returned ``long-running operation`` will
        have a name of the format ``<instance_name>/operations/<operation_id>`` and
        can be used to track the instance modification.  The
        ``metadata`` field type is
        ``UpdateInstanceMetadata``.
        The ``response`` field type is
        ``Instance``, if successful.

        Authorization requires ``spanner.instances.update`` permission on
        resource ``name``.

        Example:
            >>> from google.cloud import spanner_admin_instance_v1
            >>>
            >>> client = spanner_admin_instance_v1.InstanceAdminClient()
            >>>
            >>> instance = {}
            >>> field_mask = {}
            >>>
            >>> response = client.update_instance(instance, field_mask)
            >>>
            >>> def callback(operation_future):
            ...     # Handle result.
            ...     result = operation_future.result()
            >>>
            >>> response.add_done_callback(callback)
            >>>
            >>> # Handle metadata.
            >>> metadata = response.metadata()

        Args:
            instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to update, which must always include the instance
                name.  Otherwise, only fields mentioned in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.field_mask] need be included.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance`
            field_mask (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.FieldMask]): Required. A mask specifying which fields in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.instance] should be updated.
                The field mask must always be specified; this prevents any future fields in
                [][google.spanner.admin.instance.v1.Instance] from being erased accidentally by clients that do not know
                about them.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_admin_instance_v1.types.FieldMask`
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_admin_instance_v1.types._OperationFuture` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_instance_admin_pb2.UpdateInstanceRequest(
            instance=instance, field_mask=field_mask)
        return google.gax._OperationFuture(
            self._update_instance(request, options), self.operations_client,
            spanner_instance_admin_pb2.Instance,
            spanner_instance_admin_pb2.UpdateInstanceMetadata, options)

    def delete_instance(self, name, options=None):
        """
        Deletes an instance.

        Immediately upon completion of the request:

        * Billing ceases for all of the instance's reserved resources.

        Soon afterward:

        * The instance and *all of its databases* immediately and
          irrevocably disappear from the API. All data in the databases
          is permanently deleted.

        Example:
            >>> from google.cloud import spanner_admin_instance_v1
            >>>
            >>> client = spanner_admin_instance_v1.InstanceAdminClient()
            >>>
            >>> name = client.instance_path('[PROJECT]', '[INSTANCE]')
            >>>
            >>> client.delete_instance(name)

        Args:
            name (str): Required. The name of the instance to be deleted. Values are of the form
                ``projects/<project>/instances/<instance>``
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_instance_admin_pb2.DeleteInstanceRequest(name=name)
        self._delete_instance(request, options)

    def set_iam_policy(self, resource, policy, options=None):
        """
        Sets the access control policy on an instance resource. Replaces any
        existing policy.

        Authorization requires ``spanner.instances.setIamPolicy`` on
        ``resource``.

        Example:
            >>> from google.cloud import spanner_admin_instance_v1
            >>>
            >>> client = spanner_admin_instance_v1.InstanceAdminClient()
            >>>
            >>> resource = client.instance_path('[PROJECT]', '[INSTANCE]')
            >>> policy = {}
            >>>
            >>> response = client.set_iam_policy(resource, policy)

        Args:
            resource (str): REQUIRED: The resource for which the policy is being specified.
                ``resource`` is usually specified as a path. For example, a Project
                resource is specified as ``projects/{project}``.
            policy (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Policy]): REQUIRED: The complete policy to be applied to the ``resource``. The size of
                the policy is limited to a few 10s of KB. An empty policy is a
                valid policy but certain Cloud Platform services (such as Projects)
                might reject them.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_admin_instance_v1.types.Policy`
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_admin_instance_v1.types.Policy` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_policy_pb2.SetIamPolicyRequest(resource=resource,
                                                     policy=policy)
        return self._set_iam_policy(request, options)

    def get_iam_policy(self, resource, options=None):
        """
        Gets the access control policy for an instance resource. Returns an empty
        policy if an instance exists but does not have a policy set.

        Authorization requires ``spanner.instances.getIamPolicy`` on
        ``resource``.

        Example:
            >>> from google.cloud import spanner_admin_instance_v1
            >>>
            >>> client = spanner_admin_instance_v1.InstanceAdminClient()
            >>>
            >>> resource = client.instance_path('[PROJECT]', '[INSTANCE]')
            >>>
            >>> response = client.get_iam_policy(resource)

        Args:
            resource (str): REQUIRED: The resource for which the policy is being requested.
                ``resource`` is usually specified as a path. For example, a Project
                resource is specified as ``projects/{project}``.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_admin_instance_v1.types.Policy` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_policy_pb2.GetIamPolicyRequest(resource=resource)
        return self._get_iam_policy(request, options)

    def test_iam_permissions(self, resource, permissions, options=None):
        """
        Returns permissions that the caller has on the specified instance resource.

        Attempting this RPC on a non-existent Cloud Spanner instance resource will
        result in a NOT_FOUND error if the user has ``spanner.instances.list``
        permission on the containing Google Cloud Project. Otherwise returns an
        empty set of permissions.

        Example:
            >>> from google.cloud import spanner_admin_instance_v1
            >>>
            >>> client = spanner_admin_instance_v1.InstanceAdminClient()
            >>>
            >>> resource = client.instance_path('[PROJECT]', '[INSTANCE]')
            >>> permissions = []
            >>>
            >>> response = client.test_iam_permissions(resource, permissions)

        Args:
            resource (str): REQUIRED: The resource for which the policy detail is being requested.
                ``resource`` is usually specified as a path. For example, a Project
                resource is specified as ``projects/{project}``.
            permissions (list[str]): The set of permissions to check for the ``resource``. Permissions with
                wildcards (such as '*' or 'storage.*') are not allowed. For more
                information see
                `IAM Overview <https://cloud.google.com/iam/docs/overview#permissions>`_.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_admin_instance_v1.types.TestIamPermissionsResponse` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_policy_pb2.TestIamPermissionsRequest(
            resource=resource, permissions=permissions)
        return self._test_iam_permissions(request, options)
class LoggingServiceV2Api(object):
    """Service for ingesting and querying logs."""

    SERVICE_ADDRESS = 'logging.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _CODE_GEN_NAME_VERSION = 'gapic/0.1.0'

    _GAX_VERSION = pkg_resources.get_distribution('google-gax').version

    _PAGE_DESCRIPTORS = {
        'list_log_entries':
        _PageDesc('page_token', 'next_page_token', 'entries'),
        'list_monitored_resource_descriptors':
        _PageDesc('page_token', 'next_page_token', 'resource_descriptors')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = (
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/cloud-platform.read-only',
        'https://www.googleapis.com/auth/logging.admin',
        'https://www.googleapis.com/auth/logging.read',
        'https://www.googleapis.com/auth/logging.write',
    )

    _PARENT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')
    _LOG_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/logs/{log}')

    @classmethod
    def parent_path(cls, project):
        """Returns a fully-qualified parent resource name string."""
        return cls._PARENT_PATH_TEMPLATE.render({
            'project': project,
        })

    @classmethod
    def log_path(cls, project, log):
        """Returns a fully-qualified log resource name string."""
        return cls._LOG_PATH_TEMPLATE.render({
            'project': project,
            'log': log,
        })

    @classmethod
    def match_project_from_parent_name(cls, parent_name):
        """Parses the project from a parent resource.

        Args:
          parent_name (string): A fully-qualified path representing a parent
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PARENT_PATH_TEMPLATE.match(parent_name).get('project')

    @classmethod
    def match_project_from_log_name(cls, log_name):
        """Parses the project from a log resource.

        Args:
          log_name (string): A fully-qualified path representing a log
            resource.

        Returns:
          A string representing the project.
        """
        return cls._LOG_PATH_TEMPLATE.match(log_name).get('project')

    @classmethod
    def match_log_from_log_name(cls, log_name):
        """Parses the log from a log resource.

        Args:
          log_name (string): A fully-qualified path representing a log
            resource.

        Returns:
          A string representing the log.
        """
        return cls._LOG_PATH_TEMPLATE.match(log_name).get('log')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 metadata_transformer=None,
                 ssl_creds=None,
                 scopes=None,
                 client_config=None,
                 app_name='gax',
                 app_version=_GAX_VERSION):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          ssl_creds (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          metadata_transformer (Callable[[], list]): A function that creates
             the metadata for requests.
          app_name (string): The codename of the calling service.
          app_version (string): The version of the calling service.

        Returns:
          A LoggingServiceV2Api object.
        """
        if scopes is None:
            scopes = self._ALL_SCOPES
        if client_config is None:
            client_config = {}
        goog_api_client = '{}/{} {} gax/{} python/{}'.format(
            app_name, app_version, self._CODE_GEN_NAME_VERSION,
            self._GAX_VERSION, platform.python_version())
        metadata = [('x-goog-api-client', goog_api_client)]
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'logging_service_v2_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.logging.v2.LoggingServiceV2',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            kwargs={'metadata': metadata},
            page_descriptors=self._PAGE_DESCRIPTORS)
        self.logging_service_v2_stub = config.create_stub(
            logging_pb2.LoggingServiceV2Stub,
            service_path,
            port,
            ssl_creds=ssl_creds,
            channel=channel,
            metadata_transformer=metadata_transformer,
            scopes=scopes)

        self._delete_log = api_callable.create_api_call(
            self.logging_service_v2_stub.DeleteLog,
            settings=defaults['delete_log'])
        self._write_log_entries = api_callable.create_api_call(
            self.logging_service_v2_stub.WriteLogEntries,
            settings=defaults['write_log_entries'])
        self._list_log_entries = api_callable.create_api_call(
            self.logging_service_v2_stub.ListLogEntries,
            settings=defaults['list_log_entries'])
        self._list_monitored_resource_descriptors = api_callable.create_api_call(
            self.logging_service_v2_stub.ListMonitoredResourceDescriptors,
            settings=defaults['list_monitored_resource_descriptors'])

    # Service calls
    def delete_log(self, log_name, options=None):
        """
        Deletes a log and all its log entries.
        The log will reappear if it receives new entries.

        Example:
          >>> from google.cloud.gapic.logging.v2 import logging_service_v2_api
          >>> api = logging_service_v2_api.LoggingServiceV2Api()
          >>> log_name = api.log_path('[PROJECT]', '[LOG]')
          >>> api.delete_log(log_name)

        Args:
          log_name (string): Required. The resource name of the log to delete.  Example:
            ``\"projects/my-project/logs/syslog\"``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = logging_pb2.DeleteLogRequest(log_name=log_name)
        self._delete_log(request, options)

    def write_log_entries(self,
                          entries,
                          log_name='',
                          resource=None,
                          labels=None,
                          partial_success=False,
                          options=None):
        """
        Writes log entries to Stackdriver Logging.  All log entries are
        written by this method.

        Example:
          >>> from google.cloud.gapic.logging.v2 import logging_service_v2_api
          >>> from google.logging.v2 import log_entry_pb2
          >>> api = logging_service_v2_api.LoggingServiceV2Api()
          >>> entries = []
          >>> response = api.write_log_entries(entries)

        Args:
          log_name (string): Optional. A default log resource name that is assigned to all log entries
            in ``entries`` that do not specify a value for ``log_name``.  Example:
            ``\"projects/my-project/logs/syslog\"``.  See
            ``LogEntry``.
          resource (:class:`google.api.monitored_resource_pb2.MonitoredResource`): Optional. A default monitored resource object that is assigned to all log
            entries in ``entries`` that do not specify a value for ``resource``. Example:

                { \"type\": \"gce_instance\",
                  \"labels\": {
                    \"zone\": \"us-central1-a\", \"instance_id\": \"00000000000000000000\" }}

            See ``LogEntry``.
          labels (dict[string -> :class:`google.logging.v2.logging_pb2.WriteLogEntriesRequest.LabelsEntry`]): Optional. Default labels that are added to the ``labels`` field of all log
            entries in ``entries``. If a log entry already has a label with the same key
            as a label in this parameter, then the log entry's label is not changed.
            See ``LogEntry``.
          entries (list[:class:`google.logging.v2.log_entry_pb2.LogEntry`]): Required. The log entries to write. Values supplied for the fields
            ``log_name``, ``resource``, and ``labels`` in this ``entries.write`` request are
            added to those log entries that do not provide their own values for the
            fields.

            To improve throughput and to avoid exceeding the
            `quota limit <https://cloud.google.com/logging/quota-policy>`_ for calls to ``entries.write``,
            you should write multiple log entries at once rather than
            calling this method for each individual log entry.
          partial_success (bool): Optional. Whether valid entries should be written even if some other
            entries fail due to INVALID_ARGUMENT or PERMISSION_DENIED errors. If any
            entry is not written, the response status will be the error associated
            with one of the failed entries and include error details in the form of
            WriteLogEntriesPartialErrors.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        if resource is None:
            resource = monitored_resource_pb2.MonitoredResource()
        if labels is None:
            labels = []
        request = logging_pb2.WriteLogEntriesRequest(
            entries=entries,
            log_name=log_name,
            resource=resource,
            labels=labels,
            partial_success=partial_success)
        self._write_log_entries(request, options)

    def list_log_entries(self,
                         project_ids,
                         resource_names=None,
                         filter_='',
                         order_by='',
                         page_size=0,
                         options=None):
        """
        Lists log entries.  Use this method to retrieve log entries from Cloud
        Logging.  For ways to export log entries, see
        `Exporting Logs <https://cloud.google.com/logging/docs/export>`_.

        Example:
          >>> from google.cloud.gapic.logging.v2 import logging_service_v2_api
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = logging_service_v2_api.LoggingServiceV2Api()
          >>> project_ids = []
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_log_entries(project_ids):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_log_entries(project_ids, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          project_ids (list[string]): Deprecated. One or more project identifiers or project numbers from which
            to retrieve log entries.  Examples: ``\"my-project-1A\"``, ``\"1234567890\"``. If
            present, these project identifiers are converted to resource format and
            added to the list of resources in ``resourceNames``. Callers should use
            ``resourceNames`` rather than this parameter.
          resource_names (list[string]): Optional. One or more cloud resources from which to retrieve log entries.
            Example: ``\"projects/my-project-1A\"``, ``\"projects/1234567890\"``.  Projects
            listed in ``projectIds`` are added to this list.
          filter_ (string): Optional. A filter that chooses which log entries to return.  See `Advanced
            Logs Filters <https://cloud.google.com/logging/docs/view/advanced_filters>`_.  Only log entries that
            match the filter are returned.  An empty filter matches all log entries.
          order_by (string): Optional. How the results should be sorted.  Presently, the only permitted
            values are ``\"timestamp asc\"`` (default) and ``\"timestamp desc\"``. The first
            option returns entries in order of increasing values of
            ``LogEntry.timestamp`` (oldest first), and the second option returns entries
            in order of decreasing timestamps (newest first).  Entries with equal
            timestamps are returned in order of ``LogEntry.insertId``.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.logging.v2.log_entry_pb2.LogEntry` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        if resource_names is None:
            resource_names = []
        request = logging_pb2.ListLogEntriesRequest(
            project_ids=project_ids,
            resource_names=resource_names,
            filter=filter_,
            order_by=order_by,
            page_size=page_size)
        return self._list_log_entries(request, options)

    def list_monitored_resource_descriptors(self, page_size=0, options=None):
        """
        Lists the monitored resource descriptors used by Stackdriver Logging.

        Example:
          >>> from google.cloud.gapic.logging.v2 import logging_service_v2_api
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = logging_service_v2_api.LoggingServiceV2Api()
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_monitored_resource_descriptors():
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_monitored_resource_descriptors(options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.api.monitored_resource_pb2.MonitoredResourceDescriptor` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = logging_pb2.ListMonitoredResourceDescriptorsRequest(
            page_size=page_size)
        return self._list_monitored_resource_descriptors(request, options)
class DlpServiceClient(object):
    """
    The DLP API is a service that allows clients
    to detect the presence of Personally Identifiable Information (PII) and other
    privacy-sensitive data in user-supplied, unstructured data streams, like text
    blocks or images.
    The service also includes methods for sensitive data redaction and
    scheduling of data scans on Google Cloud Platform based data sets.
    """

    SERVICE_ADDRESS = 'dlp.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = ('https://www.googleapis.com/auth/cloud-platform', )

    _RESULT_PATH_TEMPLATE = path_template.PathTemplate(
        'inspect/results/{result}')

    @classmethod
    def result_path(cls, result):
        """Returns a fully-qualified result resource name string."""
        return cls._RESULT_PATH_TEMPLATE.render({
            'result': result,
        })

    @classmethod
    def match_result_from_result_name(cls, result_name):
        """Parses the result from a result resource.

        Args:
          result_name (string): A fully-qualified path representing a result
            resource.

        Returns:
          A string representing the result.
        """
        return cls._RESULT_PATH_TEMPLATE.match(result_name).get('result')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 credentials=None,
                 ssl_credentials=None,
                 scopes=None,
                 client_config=None,
                 app_name=None,
                 app_version='',
                 lib_name=None,
                 lib_version='',
                 metrics_headers=()):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          credentials (object): The authorization credentials to attach to
            requests. These credentials identify this application to the
            service.
          ssl_credentials (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          scopes (list[string]): A list of OAuth2 scopes to attach to requests.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          app_name (string): The name of the application calling
            the service. Recommended for analytics purposes.
          app_version (string): The version of the application calling
            the service. Recommended for analytics purposes.
          lib_name (string): The API library software used for calling
            the service. (Unless you are writing an API client itself,
            leave this as default.)
          lib_version (string): The API library software version used
            for calling the service. (Unless you are writing an API client
            itself, leave this as default.)
          metrics_headers (dict): A dictionary of values for tracking
            client library metrics. Ultimately serializes to a string
            (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be
            considered private.

        Returns:
          A DlpServiceClient object.
        """
        # Unless the calling application specifically requested
        # OAuth scopes, request everything.
        if scopes is None:
            scopes = self._ALL_SCOPES

        # Initialize an empty client config, if none is set.
        if client_config is None:
            client_config = {}

        # Initialize metrics_headers as an ordered dictionary
        # (cuts down on cardinality of the resulting string slightly).
        metrics_headers = collections.OrderedDict(metrics_headers)
        metrics_headers['gl-python'] = platform.python_version()

        # The library may or may not be set, depending on what is
        # calling this client. Newer client libraries set the library name
        # and version.
        if lib_name:
            metrics_headers[lib_name] = lib_version

        # Finally, track the GAPIC package version.
        metrics_headers['gapic'] = pkg_resources.get_distribution(
            'gapic-google-cloud-dlp-v2beta1', ).version

        # Load the configuration defaults.
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'dlp_service_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.privacy.dlp.v2beta1.DlpService',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            metrics_headers=metrics_headers,
        )
        self.dlp_service_stub = config.create_stub(
            dlp_pb2.DlpServiceStub,
            channel=channel,
            service_path=service_path,
            service_port=port,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)

        self._inspect_content = api_callable.create_api_call(
            self.dlp_service_stub.InspectContent,
            settings=defaults['inspect_content'])
        self._redact_content = api_callable.create_api_call(
            self.dlp_service_stub.RedactContent,
            settings=defaults['redact_content'])
        self._create_inspect_operation = api_callable.create_api_call(
            self.dlp_service_stub.CreateInspectOperation,
            settings=defaults['create_inspect_operation'])
        self._list_inspect_findings = api_callable.create_api_call(
            self.dlp_service_stub.ListInspectFindings,
            settings=defaults['list_inspect_findings'])
        self._list_info_types = api_callable.create_api_call(
            self.dlp_service_stub.ListInfoTypes,
            settings=defaults['list_info_types'])
        self._list_root_categories = api_callable.create_api_call(
            self.dlp_service_stub.ListRootCategories,
            settings=defaults['list_root_categories'])

    # Service calls
    def inspect_content(self, inspect_config, items, options=None):
        """
        Find potentially sensitive info in a list of strings.
        This method has limits on input size, processing time, and output size.

        Example:
          >>> from google.cloud.gapic.privacy.dlp.v2beta1 import dlp_service_client
          >>> from google.cloud.proto.privacy.dlp.v2beta1 import dlp_pb2
          >>> client = dlp_service_client.DlpServiceClient()
          >>> inspect_config = dlp_pb2.InspectConfig()
          >>> items = []
          >>> response = client.inspect_content(inspect_config, items)

        Args:
          inspect_config (:class:`google.cloud.proto.privacy.dlp.v2beta1.dlp_pb2.InspectConfig`): Configuration for the inspector.
          items (list[:class:`google.cloud.proto.privacy.dlp.v2beta1.dlp_pb2.ContentItem`]): The list of items to inspect. Items in a single request are
            considered \"related\" unless inspect_config.independent_inputs is true.
            Up to 100 are allowed per request.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.privacy.dlp.v2beta1.dlp_pb2.InspectContentResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = dlp_pb2.InspectContentRequest(inspect_config=inspect_config,
                                                items=items)
        return self._inspect_content(request, options)

    def redact_content(self,
                       inspect_config,
                       items,
                       replace_configs,
                       options=None):
        """
        Redact potentially sensitive info from a list of strings.
        This method has limits on input size, processing time, and output size.

        Example:
          >>> from google.cloud.gapic.privacy.dlp.v2beta1 import dlp_service_client
          >>> from google.cloud.proto.privacy.dlp.v2beta1 import dlp_pb2
          >>> client = dlp_service_client.DlpServiceClient()
          >>> inspect_config = dlp_pb2.InspectConfig()
          >>> items = []
          >>> replace_configs = []
          >>> response = client.redact_content(inspect_config, items, replace_configs)

        Args:
          inspect_config (:class:`google.cloud.proto.privacy.dlp.v2beta1.dlp_pb2.InspectConfig`): Configuration for the inspector.
          items (list[:class:`google.cloud.proto.privacy.dlp.v2beta1.dlp_pb2.ContentItem`]): The list of items to inspect. Up to 100 are allowed per request.
          replace_configs (list[:class:`google.cloud.proto.privacy.dlp.v2beta1.dlp_pb2.RedactContentRequest.ReplaceConfig`]): The strings to replace findings with. Must specify at least one.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.privacy.dlp.v2beta1.dlp_pb2.RedactContentResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = dlp_pb2.RedactContentRequest(inspect_config=inspect_config,
                                               items=items,
                                               replace_configs=replace_configs)
        return self._redact_content(request, options)

    def create_inspect_operation(self,
                                 inspect_config,
                                 storage_config,
                                 output_config,
                                 options=None):
        """
        Schedule a job scanning content in a Google Cloud Platform data repository.

        Example:
          >>> from google.cloud.gapic.privacy.dlp.v2beta1 import dlp_service_client
          >>> from google.cloud.proto.privacy.dlp.v2beta1 import dlp_pb2
          >>> from google.cloud.proto.privacy.dlp.v2beta1 import storage_pb2
          >>> client = dlp_service_client.DlpServiceClient()
          >>> inspect_config = dlp_pb2.InspectConfig()
          >>> storage_config = storage_pb2.StorageConfig()
          >>> output_config = dlp_pb2.OutputStorageConfig()
          >>> response = client.create_inspect_operation(inspect_config, storage_config, output_config)

        Args:
          inspect_config (:class:`google.cloud.proto.privacy.dlp.v2beta1.dlp_pb2.InspectConfig`): Configuration for the inspector.
          storage_config (:class:`google.cloud.proto.privacy.dlp.v2beta1.storage_pb2.StorageConfig`): Specification of the data set to process.
          output_config (:class:`google.cloud.proto.privacy.dlp.v2beta1.dlp_pb2.OutputStorageConfig`): Optional location to store findings. The bucket must already exist and
            the Google APIs service account for DLP must have write permission to
            write to the given bucket.
            Results will be split over multiple csv files with each file name matching
            the pattern \"[operation_id] + [count].csv\".
            The operation_id will match the identifier for the Operation,
            and the [count] is a counter used for tracking the number of files written.
            The CSV file(s) contain the following columns regardless of storage type
            scanned: id, info_type, likelihood, byte size of finding, quote, time_stamp
            For cloud storage the next two columns are: file_path, start_offset
            For datastore the next two columns are: project_id, namespace_id, path,
            ::

                column_name, offset.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.longrunning.operations_pb2.Operation` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = dlp_pb2.CreateInspectOperationRequest(
            inspect_config=inspect_config,
            storage_config=storage_config,
            output_config=output_config)
        return self._create_inspect_operation(request, options)

    def list_inspect_findings(self,
                              name,
                              page_size=None,
                              page_token=None,
                              options=None):
        """
        Returns list of results for given inspect operation result set id.

        Example:
          >>> from google.cloud.gapic.privacy.dlp.v2beta1 import dlp_service_client
          >>> client = dlp_service_client.DlpServiceClient()
          >>> name = client.result_path('[RESULT]')
          >>> response = client.list_inspect_findings(name)

        Args:
          name (string): Identifier of the results set returned as metadata of
            the longrunning operation created by a call to CreateInspectOperation.
            Should be in the format of ``inspect/results/{id}.
          page_size (int): Maximum number of results to return.
            If 0, the implementation will select a reasonable value.
          page_token (string): The value returned by the last ``ListInspectFindingsResponse``; indicates
            that this is a continuation of a prior ``ListInspectFindings`` call, and that
            the system should return the next page of data.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.privacy.dlp.v2beta1.dlp_pb2.ListInspectFindingsResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = dlp_pb2.ListInspectFindingsRequest(name=name,
                                                     page_size=page_size,
                                                     page_token=page_token)
        return self._list_inspect_findings(request, options)

    def list_info_types(self, category, language_code, options=None):
        """
        Returns sensitive information types for given category.

        Example:
          >>> from google.cloud.gapic.privacy.dlp.v2beta1 import dlp_service_client
          >>> client = dlp_service_client.DlpServiceClient()
          >>> category = ''
          >>> language_code = ''
          >>> response = client.list_info_types(category, language_code)

        Args:
          category (string): Category name as returned by ListRootCategories.
          language_code (string): Optional BCP-47 language code for localized info type friendly
            names. If omitted, or if localized strings are not available,
            en-US strings will be returned.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.privacy.dlp.v2beta1.dlp_pb2.ListInfoTypesResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = dlp_pb2.ListInfoTypesRequest(category=category,
                                               language_code=language_code)
        return self._list_info_types(request, options)

    def list_root_categories(self, language_code, options=None):
        """
        Returns the list of root categories of sensitive information.

        Example:
          >>> from google.cloud.gapic.privacy.dlp.v2beta1 import dlp_service_client
          >>> client = dlp_service_client.DlpServiceClient()
          >>> language_code = ''
          >>> response = client.list_root_categories(language_code)

        Args:
          language_code (string): Optional language code for localized friendly category names.
            If omitted or if localized strings are not available,
            en-US strings will be returned.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.privacy.dlp.v2beta1.dlp_pb2.ListRootCategoriesResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = dlp_pb2.ListRootCategoriesRequest(
            language_code=language_code)
        return self._list_root_categories(request, options)
Exemple #13
0
class BigtableApi(object):
    """Service for reading from and writing to existing Bigtable tables."""

    SERVICE_ADDRESS = 'bigtable.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _CODE_GEN_NAME_VERSION = 'gapic/0.1.0'

    _GAX_VERSION = pkg_resources.get_distribution('google-gax').version

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = (
        'https://www.googleapis.com/auth/bigtable.data',
        'https://www.googleapis.com/auth/bigtable.data.readonly',
        'https://www.googleapis.com/auth/cloud-bigtable.data',
        'https://www.googleapis.com/auth/cloud-bigtable.data.readonly',
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/cloud-platform.read-only',
    )

    _TABLE_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/instances/{instance}/tables/{table}')

    @classmethod
    def table_path(cls, project, instance, table):
        """Returns a fully-qualified table resource name string."""
        return cls._TABLE_PATH_TEMPLATE.render({
            'project': project,
            'instance': instance,
            'table': table,
        })

    @classmethod
    def match_project_from_table_name(cls, table_name):
        """Parses the project from a table resource.

        Args:
          table_name (string): A fully-qualified path representing a table
            resource.

        Returns:
          A string representing the project.
        """
        return cls._TABLE_PATH_TEMPLATE.match(table_name).get('project')

    @classmethod
    def match_instance_from_table_name(cls, table_name):
        """Parses the instance from a table resource.

        Args:
          table_name (string): A fully-qualified path representing a table
            resource.

        Returns:
          A string representing the instance.
        """
        return cls._TABLE_PATH_TEMPLATE.match(table_name).get('instance')

    @classmethod
    def match_table_from_table_name(cls, table_name):
        """Parses the table from a table resource.

        Args:
          table_name (string): A fully-qualified path representing a table
            resource.

        Returns:
          A string representing the table.
        """
        return cls._TABLE_PATH_TEMPLATE.match(table_name).get('table')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 metadata_transformer=None,
                 ssl_creds=None,
                 scopes=None,
                 client_config=None,
                 app_name='gax',
                 app_version=_GAX_VERSION):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          ssl_creds (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          metadata_transformer (Callable[[], list]): A function that creates
             the metadata for requests.
          app_name (string): The codename of the calling service.
          app_version (string): The version of the calling service.

        Returns:
          A BigtableApi object.
        """
        if scopes is None:
            scopes = self._ALL_SCOPES
        if client_config is None:
            client_config = {}
        goog_api_client = '{}/{} {} gax/{} python/{}'.format(
            app_name, app_version, self._CODE_GEN_NAME_VERSION,
            self._GAX_VERSION, platform.python_version())
        metadata = [('x-goog-api-client', goog_api_client)]
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'bigtable_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.bigtable.v2.Bigtable',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            kwargs={'metadata': metadata})
        self.bigtable_stub = config.create_stub(
            bigtable_pb2.BigtableStub,
            service_path,
            port,
            ssl_creds=ssl_creds,
            channel=channel,
            metadata_transformer=metadata_transformer,
            scopes=scopes)

        self._read_rows = api_callable.create_api_call(
            self.bigtable_stub.ReadRows, settings=defaults['read_rows'])
        self._sample_row_keys = api_callable.create_api_call(
            self.bigtable_stub.SampleRowKeys,
            settings=defaults['sample_row_keys'])
        self._mutate_row = api_callable.create_api_call(
            self.bigtable_stub.MutateRow, settings=defaults['mutate_row'])
        self._mutate_rows = api_callable.create_api_call(
            self.bigtable_stub.MutateRows, settings=defaults['mutate_rows'])
        self._check_and_mutate_row = api_callable.create_api_call(
            self.bigtable_stub.CheckAndMutateRow,
            settings=defaults['check_and_mutate_row'])
        self._read_modify_write_row = api_callable.create_api_call(
            self.bigtable_stub.ReadModifyWriteRow,
            settings=defaults['read_modify_write_row'])

    # Service calls
    def read_rows(self,
                  table_name,
                  rows=None,
                  filter_=None,
                  rows_limit=0,
                  options=None):
        """
        Streams back the contents of all requested rows, optionally
        applying the same Reader filter to each. Depending on their size,
        rows and cells may be broken up across multiple responses, but
        atomicity of each row will still be preserved. See the
        ReadRowsResponse documentation for details.

        Example:
          >>> from google.cloud.gapic.bigtable.v2 import bigtable_api
          >>> api = bigtable_api.BigtableApi()
          >>> table_name = api.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]')
          >>> for element in api.read_rows(table_name):
          >>>   # process element
          >>>   pass

        Args:
          table_name (string): The unique name of the table from which to read.
            Values are of the form
            ``projects/<project>/instances/<instance>/tables/<table>``.
          rows (:class:`google.bigtable.v2.data_pb2.RowSet`): The row keys and/or ranges to read. If not specified, reads from all rows.
          filter_ (:class:`google.bigtable.v2.data_pb2.RowFilter`): The filter to apply to the contents of the specified row(s). If unset,
            reads the entirety of each row.
          rows_limit (long): The read will terminate after committing to N rows' worth of results. The
            default (zero) is to return all results.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          iterator[:class:`google.bigtable.v2.bigtable_pb2.ReadRowsResponse`].

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        if rows is None:
            rows = data_pb2.RowSet()
        if filter_ is None:
            filter_ = data_pb2.RowFilter()
        request = bigtable_pb2.ReadRowsRequest(table_name=table_name,
                                               rows=rows,
                                               filter=filter_,
                                               rows_limit=rows_limit)
        return self._read_rows(request, options)

    def sample_row_keys(self, table_name, options=None):
        """
        Returns a sample of row keys in the table. The returned row keys will
        delimit contiguous sections of the table of approximately equal size,
        which can be used to break up the data for distributed tasks like
        mapreduces.

        Example:
          >>> from google.cloud.gapic.bigtable.v2 import bigtable_api
          >>> api = bigtable_api.BigtableApi()
          >>> table_name = api.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]')
          >>> for element in api.sample_row_keys(table_name):
          >>>   # process element
          >>>   pass

        Args:
          table_name (string): The unique name of the table from which to sample row keys.
            Values are of the form
            ``projects/<project>/instances/<instance>/tables/<table>``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          iterator[:class:`google.bigtable.v2.bigtable_pb2.SampleRowKeysResponse`].

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = bigtable_pb2.SampleRowKeysRequest(table_name=table_name)
        return self._sample_row_keys(request, options)

    def mutate_row(self, table_name, row_key, mutations, options=None):
        """
        Mutates a row atomically. Cells already present in the row are left
        unchanged unless explicitly changed by ``mutation``.

        Example:
          >>> from google.cloud.gapic.bigtable.v2 import bigtable_api
          >>> from google.bigtable.v2 import data_pb2
          >>> api = bigtable_api.BigtableApi()
          >>> table_name = api.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]')
          >>> row_key = ''
          >>> mutations = []
          >>> response = api.mutate_row(table_name, row_key, mutations)

        Args:
          table_name (string): The unique name of the table to which the mutation should be applied.
            Values are of the form
            ``projects/<project>/instances/<instance>/tables/<table>``.
          row_key (bytes): The key of the row to which the mutation should be applied.
          mutations (list[:class:`google.bigtable.v2.data_pb2.Mutation`]): Changes to be atomically applied to the specified row. Entries are applied
            in order, meaning that earlier mutations can be masked by later ones.
            Must contain at least one entry and at most 100000.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = bigtable_pb2.MutateRowRequest(table_name=table_name,
                                                row_key=row_key,
                                                mutations=mutations)
        self._mutate_row(request, options)

    def mutate_rows(self, table_name, entries, options=None):
        """
        Mutates multiple rows in a batch. Each individual row is mutated
        atomically as in MutateRow, but the entire batch is not executed
        atomically.

        Example:
          >>> from google.cloud.gapic.bigtable.v2 import bigtable_api
          >>> from google.bigtable.v2 import bigtable_pb2
          >>> api = bigtable_api.BigtableApi()
          >>> table_name = api.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]')
          >>> entries = []
          >>> for element in api.mutate_rows(table_name, entries):
          >>>   # process element
          >>>   pass

        Args:
          table_name (string): The unique name of the table to which the mutations should be applied.
          entries (list[:class:`google.bigtable.v2.bigtable_pb2.MutateRowsRequest.Entry`]): The row keys and corresponding mutations to be applied in bulk.
            Each entry is applied as an atomic mutation, but the entries may be
            applied in arbitrary order (even between entries for the same row).
            At least one entry must be specified, and in total the entries can
            contain at most 100000 mutations.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          iterator[:class:`google.bigtable.v2.bigtable_pb2.MutateRowsResponse`].

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = bigtable_pb2.MutateRowsRequest(table_name=table_name,
                                                 entries=entries)
        return self._mutate_rows(request, options)

    def check_and_mutate_row(self,
                             table_name,
                             row_key,
                             predicate_filter=None,
                             true_mutations=None,
                             false_mutations=None,
                             options=None):
        """
        Mutates a row atomically based on the output of a predicate Reader filter.

        Example:
          >>> from google.cloud.gapic.bigtable.v2 import bigtable_api
          >>> api = bigtable_api.BigtableApi()
          >>> table_name = api.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]')
          >>> row_key = ''
          >>> response = api.check_and_mutate_row(table_name, row_key)

        Args:
          table_name (string): The unique name of the table to which the conditional mutation should be
            applied.
            Values are of the form
            ``projects/<project>/instances/<instance>/tables/<table>``.
          row_key (bytes): The key of the row to which the conditional mutation should be applied.
          predicate_filter (:class:`google.bigtable.v2.data_pb2.RowFilter`): The filter to be applied to the contents of the specified row. Depending
            on whether or not any results are yielded, either ``true_mutations`` or
            ``false_mutations`` will be executed. If unset, checks that the row contains
            any values at all.
          true_mutations (list[:class:`google.bigtable.v2.data_pb2.Mutation`]): Changes to be atomically applied to the specified row if ``predicate_filter``
            yields at least one cell when applied to ``row_key``. Entries are applied in
            order, meaning that earlier mutations can be masked by later ones.
            Must contain at least one entry if ``false_mutations`` is empty, and at most
            100000.
          false_mutations (list[:class:`google.bigtable.v2.data_pb2.Mutation`]): Changes to be atomically applied to the specified row if ``predicate_filter``
            does not yield any cells when applied to ``row_key``. Entries are applied in
            order, meaning that earlier mutations can be masked by later ones.
            Must contain at least one entry if ``true_mutations`` is empty, and at most
            100000.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.bigtable.v2.bigtable_pb2.CheckAndMutateRowResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        if predicate_filter is None:
            predicate_filter = data_pb2.RowFilter()
        if true_mutations is None:
            true_mutations = []
        if false_mutations is None:
            false_mutations = []
        request = bigtable_pb2.CheckAndMutateRowRequest(
            table_name=table_name,
            row_key=row_key,
            predicate_filter=predicate_filter,
            true_mutations=true_mutations,
            false_mutations=false_mutations)
        return self._check_and_mutate_row(request, options)

    def read_modify_write_row(self, table_name, row_key, rules, options=None):
        """
        Modifies a row atomically. The method reads the latest existing timestamp
        and value from the specified columns and writes a new entry based on
        pre-defined read/modify/write rules. The new value for the timestamp is the
        greater of the existing timestamp or the current server time. The method
        returns the new contents of all modified cells.

        Example:
          >>> from google.cloud.gapic.bigtable.v2 import bigtable_api
          >>> from google.bigtable.v2 import data_pb2
          >>> api = bigtable_api.BigtableApi()
          >>> table_name = api.table_path('[PROJECT]', '[INSTANCE]', '[TABLE]')
          >>> row_key = ''
          >>> rules = []
          >>> response = api.read_modify_write_row(table_name, row_key, rules)

        Args:
          table_name (string): The unique name of the table to which the read/modify/write rules should be
            applied.
            Values are of the form
            ``projects/<project>/instances/<instance>/tables/<table>``.
          row_key (bytes): The key of the row to which the read/modify/write rules should be applied.
          rules (list[:class:`google.bigtable.v2.data_pb2.ReadModifyWriteRule`]): Rules specifying how the specified row's contents are to be transformed
            into writes. Entries are applied in order, meaning that earlier rules will
            affect the results of later ones.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.bigtable.v2.bigtable_pb2.ReadModifyWriteRowResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = bigtable_pb2.ReadModifyWriteRowRequest(table_name=table_name,
                                                         row_key=row_key,
                                                         rules=rules)
        return self._read_modify_write_row(request, options)
Exemple #14
0
class IAMApi(object):
    """
    Creates and manages service account objects.

    Service account is an account that belongs to your project instead
    of to an individual end user. It is used to authenticate calls
    to a Google API.

    To create a service account, specify the ``project_id`` and ``account_id``
    for the account.  The ``account_id`` is unique within the project, and used
    to generate the service account email address and a stable
    ``unique_id``.

    All other methods can identify accounts using the format
    ``projects/{project}/serviceAccounts/{account}``.
    Using ``-`` as a wildcard for the project will infer the project from
    the account. The ``account`` value can be the ``email`` address or the
    ``unique_id`` of the service account.
    """

    SERVICE_ADDRESS = 'iam.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _CODE_GEN_NAME_VERSION = 'gapic/0.1.0'

    _GAX_VERSION = pkg_resources.get_distribution('google-gax').version

    _PAGE_DESCRIPTORS = {
        'list_service_accounts':
        _PageDesc('page_token', 'next_page_token', 'accounts')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = (
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/iam',
    )

    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')
    _SERVICE_ACCOUNT_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/serviceAccounts/{service_account}')
    _KEY_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/serviceAccounts/{service_account}/keys/{key}')

    @classmethod
    def project_path(cls, project):
        """Returns a fully-qualified project resource name string."""
        return cls._PROJECT_PATH_TEMPLATE.render({
            'project': project,
        })

    @classmethod
    def service_account_path(cls, project, service_account):
        """Returns a fully-qualified service_account resource name string."""
        return cls._SERVICE_ACCOUNT_PATH_TEMPLATE.render({
            'project':
            project,
            'service_account':
            service_account,
        })

    @classmethod
    def key_path(cls, project, service_account, key):
        """Returns a fully-qualified key resource name string."""
        return cls._KEY_PATH_TEMPLATE.render({
            'project': project,
            'service_account': service_account,
            'key': key,
        })

    @classmethod
    def match_project_from_project_name(cls, project_name):
        """Parses the project from a project resource.

        Args:
          project_name (string): A fully-qualified path representing a project
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')

    @classmethod
    def match_project_from_service_account_name(cls, service_account_name):
        """Parses the project from a service_account resource.

        Args:
          service_account_name (string): A fully-qualified path representing a service_account
            resource.

        Returns:
          A string representing the project.
        """
        return cls._SERVICE_ACCOUNT_PATH_TEMPLATE.match(
            service_account_name).get('project')

    @classmethod
    def match_service_account_from_service_account_name(
            cls, service_account_name):
        """Parses the service_account from a service_account resource.

        Args:
          service_account_name (string): A fully-qualified path representing a service_account
            resource.

        Returns:
          A string representing the service_account.
        """
        return cls._SERVICE_ACCOUNT_PATH_TEMPLATE.match(
            service_account_name).get('service_account')

    @classmethod
    def match_project_from_key_name(cls, key_name):
        """Parses the project from a key resource.

        Args:
          key_name (string): A fully-qualified path representing a key
            resource.

        Returns:
          A string representing the project.
        """
        return cls._KEY_PATH_TEMPLATE.match(key_name).get('project')

    @classmethod
    def match_service_account_from_key_name(cls, key_name):
        """Parses the service_account from a key resource.

        Args:
          key_name (string): A fully-qualified path representing a key
            resource.

        Returns:
          A string representing the service_account.
        """
        return cls._KEY_PATH_TEMPLATE.match(key_name).get('service_account')

    @classmethod
    def match_key_from_key_name(cls, key_name):
        """Parses the key from a key resource.

        Args:
          key_name (string): A fully-qualified path representing a key
            resource.

        Returns:
          A string representing the key.
        """
        return cls._KEY_PATH_TEMPLATE.match(key_name).get('key')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 metadata_transformer=None,
                 ssl_creds=None,
                 scopes=None,
                 client_config=None,
                 app_name='gax',
                 app_version=_GAX_VERSION):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          ssl_creds (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          metadata_transformer (Callable[[], list]): A function that creates
             the metadata for requests.
          app_name (string): The codename of the calling service.
          app_version (string): The version of the calling service.

        Returns:
          A IAMApi object.
        """
        if scopes is None:
            scopes = self._ALL_SCOPES
        if client_config is None:
            client_config = {}
        goog_api_client = '{}/{} {} gax/{} python/{}'.format(
            app_name, app_version, self._CODE_GEN_NAME_VERSION,
            self._GAX_VERSION, platform.python_version())
        metadata = [('x-goog-api-client', goog_api_client)]
        default_client_config = json.loads(
            pkg_resources.resource_string(__name__,
                                          'iam_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.iam.admin.v1.IAM',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            kwargs={'metadata': metadata},
            page_descriptors=self._PAGE_DESCRIPTORS)
        self.iam_stub = config.create_stub(
            iam_pb2.IAMStub,
            service_path,
            port,
            ssl_creds=ssl_creds,
            channel=channel,
            metadata_transformer=metadata_transformer,
            scopes=scopes)

        self._list_service_accounts = api_callable.create_api_call(
            self.iam_stub.ListServiceAccounts,
            settings=defaults['list_service_accounts'])
        self._get_service_account = api_callable.create_api_call(
            self.iam_stub.GetServiceAccount,
            settings=defaults['get_service_account'])
        self._create_service_account = api_callable.create_api_call(
            self.iam_stub.CreateServiceAccount,
            settings=defaults['create_service_account'])
        self._update_service_account = api_callable.create_api_call(
            self.iam_stub.UpdateServiceAccount,
            settings=defaults['update_service_account'])
        self._delete_service_account = api_callable.create_api_call(
            self.iam_stub.DeleteServiceAccount,
            settings=defaults['delete_service_account'])
        self._list_service_account_keys = api_callable.create_api_call(
            self.iam_stub.ListServiceAccountKeys,
            settings=defaults['list_service_account_keys'])
        self._get_service_account_key = api_callable.create_api_call(
            self.iam_stub.GetServiceAccountKey,
            settings=defaults['get_service_account_key'])
        self._create_service_account_key = api_callable.create_api_call(
            self.iam_stub.CreateServiceAccountKey,
            settings=defaults['create_service_account_key'])
        self._delete_service_account_key = api_callable.create_api_call(
            self.iam_stub.DeleteServiceAccountKey,
            settings=defaults['delete_service_account_key'])
        self._sign_blob = api_callable.create_api_call(
            self.iam_stub.SignBlob, settings=defaults['sign_blob'])
        self._get_iam_policy = api_callable.create_api_call(
            self.iam_stub.GetIamPolicy, settings=defaults['get_iam_policy'])
        self._set_iam_policy = api_callable.create_api_call(
            self.iam_stub.SetIamPolicy, settings=defaults['set_iam_policy'])
        self._test_iam_permissions = api_callable.create_api_call(
            self.iam_stub.TestIamPermissions,
            settings=defaults['test_iam_permissions'])
        self._query_grantable_roles = api_callable.create_api_call(
            self.iam_stub.QueryGrantableRoles,
            settings=defaults['query_grantable_roles'])

    # Service calls
    def list_service_accounts(self, name, page_size=0, options=None):
        """
        Lists ``ServiceAccounts`` for a project.

        Example:
          >>> from google.cloud.gapic.iam_admin.v1 import iam_api
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = iam_api.IAMApi()
          >>> name = api.project_path('[PROJECT]')
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_service_accounts(name):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_service_accounts(name, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          name (string): Required. The resource name of the project associated with the service
            accounts, such as ``projects/my-project-123``.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.iam.admin.v1.iam_pb2.ServiceAccount` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_pb2.ListServiceAccountsRequest(name=name,
                                                     page_size=page_size)
        return self._list_service_accounts(request, options)

    def get_service_account(self, name, options=None):
        """
        Gets a ``ServiceAccount``.

        Example:
          >>> from google.cloud.gapic.iam_admin.v1 import iam_api
          >>> api = iam_api.IAMApi()
          >>> name = api.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]')
          >>> response = api.get_service_account(name)

        Args:
          name (string): The resource name of the service account in the following format:
            ``projects/{project}/serviceAccounts/{account}``.
            Using ``-`` as a wildcard for the project will infer the project from
            the account. The ``account`` value can be the ``email`` address or the
            ``unique_id`` of the service account.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.admin.v1.iam_pb2.ServiceAccount` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_pb2.GetServiceAccountRequest(name=name)
        return self._get_service_account(request, options)

    def create_service_account(self,
                               name,
                               account_id,
                               service_account=None,
                               options=None):
        """
        Creates a ``ServiceAccount``
        and returns it.

        Example:
          >>> from google.cloud.gapic.iam_admin.v1 import iam_api
          >>> api = iam_api.IAMApi()
          >>> name = api.project_path('[PROJECT]')
          >>> account_id = ''
          >>> response = api.create_service_account(name, account_id)

        Args:
          name (string): Required. The resource name of the project associated with the service
            accounts, such as ``projects/my-project-123``.
          account_id (string): Required. The account id that is used to generate the service account
            email address and a stable unique id. It is unique within a project,
            must be 6-30 characters long, and match the regular expression
            ```a-z <https://cloud.google.com[-a-z0-9]*[a-z0-9]>`_`` to comply with RFC1035.
          service_account (:class:`google.iam.admin.v1.iam_pb2.ServiceAccount`): The ``ServiceAccount`` resource to create.
            Currently, only the following values are user assignable:
            ``display_name`` .
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.admin.v1.iam_pb2.ServiceAccount` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        if service_account is None:
            service_account = iam_pb2.ServiceAccount()
        request = iam_pb2.CreateServiceAccountRequest(
            name=name, account_id=account_id, service_account=service_account)
        return self._create_service_account(request, options)

    def update_service_account(self,
                               etag,
                               name='',
                               project_id='',
                               unique_id='',
                               email='',
                               display_name='',
                               oauth2_client_id='',
                               options=None):
        """
        Updates a ``ServiceAccount``.
        Currently, only the following fields are updatable:
        ``display_name`` .
        The ``etag`` is mandatory.

        Example:
          >>> from google.cloud.gapic.iam_admin.v1 import iam_api
          >>> api = iam_api.IAMApi()
          >>> etag = ''
          >>> response = api.update_service_account(etag)

        Args:
          name (string): The resource name of the service account in the following format:
            ``projects/{project}/serviceAccounts/{account}``.

            Requests using ``-`` as a wildcard for the project will infer the project
            from the ``account`` and the ``account`` value can be the ``email`` address or
            the ``unique_id`` of the service account.

            In responses the resource name will always be in the format
            ``projects/{project}/serviceAccounts/{email}``.
          project_id (string): @OutputOnly The id of the project that owns the service account.
          unique_id (string): @OutputOnly The unique and stable id of the service account.
          email (string): @OutputOnly The email address of the service account.
          display_name (string): Optional. A user-specified description of the service account.  Must be
            fewer than 100 UTF-8 bytes.
          etag (bytes): Used to perform a consistent read-modify-write.
          oauth2_client_id (string): @OutputOnly. The OAuth2 client id for the service account.
            This is used in conjunction with the OAuth2 clientconfig API to make
            three legged OAuth2 (3LO) flows to access the data of Google users.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.admin.v1.iam_pb2.ServiceAccount` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_pb2.ServiceAccount(etag=etag,
                                         name=name,
                                         project_id=project_id,
                                         unique_id=unique_id,
                                         email=email,
                                         display_name=display_name,
                                         oauth2_client_id=oauth2_client_id)
        return self._update_service_account(request, options)

    def delete_service_account(self, name, options=None):
        """
        Deletes a ``ServiceAccount``.

        Example:
          >>> from google.cloud.gapic.iam_admin.v1 import iam_api
          >>> api = iam_api.IAMApi()
          >>> name = api.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]')
          >>> api.delete_service_account(name)

        Args:
          name (string): The resource name of the service account in the following format:
            ``projects/{project}/serviceAccounts/{account}``.
            Using ``-`` as a wildcard for the project will infer the project from
            the account. The ``account`` value can be the ``email`` address or the
            ``unique_id`` of the service account.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_pb2.DeleteServiceAccountRequest(name=name)
        self._delete_service_account(request, options)

    def list_service_account_keys(self, name, key_types=None, options=None):
        """
        Lists ``ServiceAccountKeys``.

        Example:
          >>> from google.cloud.gapic.iam_admin.v1 import iam_api
          >>> api = iam_api.IAMApi()
          >>> name = api.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]')
          >>> response = api.list_service_account_keys(name)

        Args:
          name (string): The resource name of the service account in the following format:
            ``projects/{project}/serviceAccounts/{account}``.

            Using ``-`` as a wildcard for the project, will infer the project from
            the account. The ``account`` value can be the ``email`` address or the
            ``unique_id`` of the service account.
          key_types (list[enum :class:`google.cloud.gapic.iam_admin.v1.enums.ListServiceAccountKeysRequest.KeyType`]): Filters the types of keys the user wants to include in the list
            response. Duplicate key types are not allowed. If no key type
            is provided, all keys are returned.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.admin.v1.iam_pb2.ListServiceAccountKeysResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        if key_types is None:
            key_types = []
        request = iam_pb2.ListServiceAccountKeysRequest(name=name,
                                                        key_types=key_types)
        return self._list_service_account_keys(request, options)

    def get_service_account_key(self,
                                name,
                                public_key_type=None,
                                options=None):
        """
        Gets the ``ServiceAccountKey``
        by key id.

        Example:
          >>> from google.cloud.gapic.iam_admin.v1 import iam_api
          >>> api = iam_api.IAMApi()
          >>> name = api.key_path('[PROJECT]', '[SERVICE_ACCOUNT]', '[KEY]')
          >>> response = api.get_service_account_key(name)

        Args:
          name (string): The resource name of the service account key in the following format:
            ``projects/{project}/serviceAccounts/{account}/keys/{key}``.

            Using ``-`` as a wildcard for the project will infer the project from
            the account. The ``account`` value can be the ``email`` address or the
            ``unique_id`` of the service account.
          public_key_type (enum :class:`google.cloud.gapic.iam_admin.v1.enums.ServiceAccountPublicKeyType`): The output format of the public key requested.
            X509_PEM is the default output format.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.admin.v1.iam_pb2.ServiceAccountKey` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        if public_key_type is None:
            public_key_type = enums.ServiceAccountPublicKeyType.TYPE_NONE
        request = iam_pb2.GetServiceAccountKeyRequest(
            name=name, public_key_type=public_key_type)
        return self._get_service_account_key(request, options)

    def create_service_account_key(self,
                                   name,
                                   private_key_type=None,
                                   key_algorithm=None,
                                   options=None):
        """
        Creates a ``ServiceAccountKey``
        and returns it.

        Example:
          >>> from google.cloud.gapic.iam_admin.v1 import iam_api
          >>> api = iam_api.IAMApi()
          >>> name = api.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]')
          >>> response = api.create_service_account_key(name)

        Args:
          name (string): The resource name of the service account in the following format:
            ``projects/{project}/serviceAccounts/{account}``.
            Using ``-`` as a wildcard for the project will infer the project from
            the account. The ``account`` value can be the ``email`` address or the
            ``unique_id`` of the service account.
          private_key_type (enum :class:`google.cloud.gapic.iam_admin.v1.enums.ServiceAccountPrivateKeyType`): The output format of the private key. ``GOOGLE_CREDENTIALS_FILE`` is the
            default output format.
          key_algorithm (enum :class:`google.cloud.gapic.iam_admin.v1.enums.ServiceAccountKeyAlgorithm`): Which type of key and algorithm to use for the key.
            The default is currently a 4K RSA key.  However this may change in the
            future.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.admin.v1.iam_pb2.ServiceAccountKey` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        if private_key_type is None:
            private_key_type = enums.ServiceAccountPrivateKeyType.TYPE_UNSPECIFIED
        if key_algorithm is None:
            key_algorithm = enums.ServiceAccountKeyAlgorithm.KEY_ALG_UNSPECIFIED
        request = iam_pb2.CreateServiceAccountKeyRequest(
            name=name,
            private_key_type=private_key_type,
            key_algorithm=key_algorithm)
        return self._create_service_account_key(request, options)

    def delete_service_account_key(self, name, options=None):
        """
        Deletes a ``ServiceAccountKey``.

        Example:
          >>> from google.cloud.gapic.iam_admin.v1 import iam_api
          >>> api = iam_api.IAMApi()
          >>> name = api.key_path('[PROJECT]', '[SERVICE_ACCOUNT]', '[KEY]')
          >>> api.delete_service_account_key(name)

        Args:
          name (string): The resource name of the service account key in the following format:
            ``projects/{project}/serviceAccounts/{account}/keys/{key}``.
            Using ``-`` as a wildcard for the project will infer the project from
            the account. The ``account`` value can be the ``email`` address or the
            ``unique_id`` of the service account.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_pb2.DeleteServiceAccountKeyRequest(name=name)
        self._delete_service_account_key(request, options)

    def sign_blob(self, name, bytes_to_sign, options=None):
        """
        Signs a blob using a service account's system-managed private key.

        Example:
          >>> from google.cloud.gapic.iam_admin.v1 import iam_api
          >>> api = iam_api.IAMApi()
          >>> name = api.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]')
          >>> bytes_to_sign = ''
          >>> response = api.sign_blob(name, bytes_to_sign)

        Args:
          name (string): The resource name of the service account in the following format:
            ``projects/{project}/serviceAccounts/{account}``.
            Using ``-`` as a wildcard for the project will infer the project from
            the account. The ``account`` value can be the ``email`` address or the
            ``unique_id`` of the service account.
          bytes_to_sign (bytes): The bytes to sign.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.admin.v1.iam_pb2.SignBlobResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_pb2.SignBlobRequest(name=name,
                                          bytes_to_sign=bytes_to_sign)
        return self._sign_blob(request, options)

    def get_iam_policy(self, resource, options=None):
        """
        Returns the IAM access control policy for a
        ``ServiceAccount``.

        Example:
          >>> from google.cloud.gapic.iam_admin.v1 import iam_api
          >>> api = iam_api.IAMApi()
          >>> resource = api.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]')
          >>> response = api.get_iam_policy(resource)

        Args:
          resource (string): REQUIRED: The resource for which the policy is being requested.
            ``resource`` is usually specified as a path. For example, a Project
            resource is specified as ``projects/{project}``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.v1.policy_pb2.Policy` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_policy_pb2.GetIamPolicyRequest(resource=resource)
        return self._get_iam_policy(request, options)

    def set_iam_policy(self, resource, policy, options=None):
        """
        Sets the IAM access control policy for a
        ``ServiceAccount``.

        Example:
          >>> from google.cloud.gapic.iam_admin.v1 import iam_api
          >>> from google.iam.v1 import policy_pb2
          >>> api = iam_api.IAMApi()
          >>> resource = api.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]')
          >>> policy = policy_pb2.Policy()
          >>> response = api.set_iam_policy(resource, policy)

        Args:
          resource (string): REQUIRED: The resource for which the policy is being specified.
            ``resource`` is usually specified as a path. For example, a Project
            resource is specified as ``projects/{project}``.
          policy (:class:`google.iam.v1.policy_pb2.Policy`): REQUIRED: The complete policy to be applied to the ``resource``. The size of
            the policy is limited to a few 10s of KB. An empty policy is a
            valid policy but certain Cloud Platform services (such as Projects)
            might reject them.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.v1.policy_pb2.Policy` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_policy_pb2.SetIamPolicyRequest(resource=resource,
                                                     policy=policy)
        return self._set_iam_policy(request, options)

    def test_iam_permissions(self, resource, permissions, options=None):
        """
        Tests the specified permissions against the IAM access control policy
        for a ``ServiceAccount``.

        Example:
          >>> from google.cloud.gapic.iam_admin.v1 import iam_api
          >>> api = iam_api.IAMApi()
          >>> resource = api.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]')
          >>> permissions = []
          >>> response = api.test_iam_permissions(resource, permissions)

        Args:
          resource (string): REQUIRED: The resource for which the policy detail is being requested.
            ``resource`` is usually specified as a path. For example, a Project
            resource is specified as ``projects/{project}``.
          permissions (list[string]): The set of permissions to check for the ``resource``. Permissions with
            wildcards (such as '*' or 'storage.*') are not allowed. For more
            information see
            `IAM Overview <https://cloud.google.com/iam/docs/overview#permissions>`_.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_policy_pb2.TestIamPermissionsRequest(
            resource=resource, permissions=permissions)
        return self._test_iam_permissions(request, options)

    def query_grantable_roles(self, full_resource_name, options=None):
        """
        Queries roles that can be granted on a particular resource.
        A role is grantable if it can be used as the role in a binding for a policy
        for that resource.

        Example:
          >>> from google.cloud.gapic.iam_admin.v1 import iam_api
          >>> api = iam_api.IAMApi()
          >>> full_resource_name = ''
          >>> response = api.query_grantable_roles(full_resource_name)

        Args:
          full_resource_name (string): Required. The full resource name to query from the list of grantable roles.

            The name follows the Google Cloud Platform resource format.
            For example, a Cloud Platform project with id ``my-project`` will be named
            ``//cloudresourcemanager.googleapis.com/projects/my-project``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.admin.v1.iam_pb2.QueryGrantableRolesResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_pb2.QueryGrantableRolesRequest(
            full_resource_name=full_resource_name)
        return self._query_grantable_roles(request, options)
class CloudFunctionsServiceClient(object):
    """A service that application uses to manipulate triggers and functions."""

    SERVICE_ADDRESS = 'cloudfunctions.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _PAGE_DESCRIPTORS = {
        'list_functions': _PageDesc('page_token', 'next_page_token',
                                    'functions')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = ('https://www.googleapis.com/auth/cloud-platform', )

    _LOCATION_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/locations/{location}')
    _FUNCTION_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/locations/{location}/functions/{function}')

    @classmethod
    def location_path(cls, project, location):
        """Returns a fully-qualified location resource name string."""
        return cls._LOCATION_PATH_TEMPLATE.render({
            'project': project,
            'location': location,
        })

    @classmethod
    def function_path(cls, project, location, function):
        """Returns a fully-qualified function resource name string."""
        return cls._FUNCTION_PATH_TEMPLATE.render({
            'project': project,
            'location': location,
            'function': function,
        })

    @classmethod
    def match_project_from_location_name(cls, location_name):
        """Parses the project from a location resource.

        Args:
          location_name (string): A fully-qualified path representing a location
            resource.

        Returns:
          A string representing the project.
        """
        return cls._LOCATION_PATH_TEMPLATE.match(location_name).get('project')

    @classmethod
    def match_location_from_location_name(cls, location_name):
        """Parses the location from a location resource.

        Args:
          location_name (string): A fully-qualified path representing a location
            resource.

        Returns:
          A string representing the location.
        """
        return cls._LOCATION_PATH_TEMPLATE.match(location_name).get('location')

    @classmethod
    def match_project_from_function_name(cls, function_name):
        """Parses the project from a function resource.

        Args:
          function_name (string): A fully-qualified path representing a function
            resource.

        Returns:
          A string representing the project.
        """
        return cls._FUNCTION_PATH_TEMPLATE.match(function_name).get('project')

    @classmethod
    def match_location_from_function_name(cls, function_name):
        """Parses the location from a function resource.

        Args:
          function_name (string): A fully-qualified path representing a function
            resource.

        Returns:
          A string representing the location.
        """
        return cls._FUNCTION_PATH_TEMPLATE.match(function_name).get('location')

    @classmethod
    def match_function_from_function_name(cls, function_name):
        """Parses the function from a function resource.

        Args:
          function_name (string): A fully-qualified path representing a function
            resource.

        Returns:
          A string representing the function.
        """
        return cls._FUNCTION_PATH_TEMPLATE.match(function_name).get('function')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 credentials=None,
                 ssl_credentials=None,
                 scopes=None,
                 client_config=None,
                 app_name=None,
                 app_version='',
                 lib_name=None,
                 lib_version='',
                 metrics_headers=()):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          credentials (object): The authorization credentials to attach to
            requests. These credentials identify this application to the
            service.
          ssl_credentials (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          scopes (list[string]): A list of OAuth2 scopes to attach to requests.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          app_name (string): The name of the application calling
            the service. Recommended for analytics purposes.
          app_version (string): The version of the application calling
            the service. Recommended for analytics purposes.
          lib_name (string): The API library software used for calling
            the service. (Unless you are writing an API client itself,
            leave this as default.)
          lib_version (string): The API library software version used
            for calling the service. (Unless you are writing an API client
            itself, leave this as default.)
          metrics_headers (dict): A dictionary of values for tracking
            client library metrics. Ultimately serializes to a string
            (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be
            considered private.

        Returns:
          A CloudFunctionsServiceClient object.
        """
        # Unless the calling application specifically requested
        # OAuth scopes, request everything.
        if scopes is None:
            scopes = self._ALL_SCOPES

        # Initialize an empty client config, if none is set.
        if client_config is None:
            client_config = {}

        # Initialize metrics_headers as an ordered dictionary
        # (cuts down on cardinality of the resulting string slightly).
        metrics_headers = collections.OrderedDict(metrics_headers)
        metrics_headers['gl-python'] = platform.python_version()

        # The library may or may not be set, depending on what is
        # calling this client. Newer client libraries set the library name
        # and version.
        if lib_name:
            metrics_headers[lib_name] = lib_version

        # Finally, track the GAPIC package version.
        metrics_headers['gapic'] = pkg_resources.get_distribution(
            'gapic-google-cloud-functions-v1beta2', ).version

        # Load the configuration defaults.
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__,
                'cloud_functions_service_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.cloud.functions.v1beta2.CloudFunctionsService',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            metrics_headers=metrics_headers,
            page_descriptors=self._PAGE_DESCRIPTORS,
        )
        self.cloud_functions_service_stub = config.create_stub(
            functions_pb2.CloudFunctionsServiceStub,
            channel=channel,
            service_path=service_path,
            service_port=port,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)

        self.operations_client = operations_client.OperationsClient(
            service_path=service_path,
            port=port,
            channel=channel,
            credentials=credentials,
            ssl_credentials=ssl_credentials,
            scopes=scopes,
            client_config=client_config,
            metrics_headers=metrics_headers,
        )

        self._list_functions = api_callable.create_api_call(
            self.cloud_functions_service_stub.ListFunctions,
            settings=defaults['list_functions'])
        self._get_function = api_callable.create_api_call(
            self.cloud_functions_service_stub.GetFunction,
            settings=defaults['get_function'])
        self._create_function = api_callable.create_api_call(
            self.cloud_functions_service_stub.CreateFunction,
            settings=defaults['create_function'])
        self._update_function = api_callable.create_api_call(
            self.cloud_functions_service_stub.UpdateFunction,
            settings=defaults['update_function'])
        self._delete_function = api_callable.create_api_call(
            self.cloud_functions_service_stub.DeleteFunction,
            settings=defaults['delete_function'])
        self._call_function = api_callable.create_api_call(
            self.cloud_functions_service_stub.CallFunction,
            settings=defaults['call_function'])

    # Service calls
    def list_functions(self, location, page_size=0, options=None):
        """
        Returns a list of functions that belong to the requested project.

        Example:
          >>> from google.cloud.functions.v1beta2 import cloud_functions_service_client
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = cloud_functions_service_client.CloudFunctionsServiceClient()
          >>> location = api.location_path('[PROJECT]', '[LOCATION]')
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_functions(location):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_functions(location, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          location (string): The project and location from which the function should be listed,
            specified in the format ``projects/*/locations/*``
            If you want to list functions in all locations, use \"-\" in place of a
            location.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.cloud.proto.functions.v1beta2.functions_pb2.CloudFunction` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = functions_pb2.ListFunctionsRequest(location=location,
                                                     page_size=page_size)
        return self._list_functions(request, options)

    def get_function(self, name, options=None):
        """
        Returns a function with the given name from the requested project.

        Example:
          >>> from google.cloud.functions.v1beta2 import cloud_functions_service_client
          >>> api = cloud_functions_service_client.CloudFunctionsServiceClient()
          >>> name = api.function_path('[PROJECT]', '[LOCATION]', '[FUNCTION]')
          >>> response = api.get_function(name)

        Args:
          name (string): The name of the function which details should be obtained.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.functions.v1beta2.functions_pb2.CloudFunction` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = functions_pb2.GetFunctionRequest(name=name)
        return self._get_function(request, options)

    def create_function(self, location, function, options=None):
        """
        Creates a new function. If a function with the given name already exists in
        the specified project, the long running operation will return
        ``ALREADY_EXISTS`` error.

        Example:
          >>> from google.cloud.functions.v1beta2 import cloud_functions_service_client
          >>> from google.cloud.proto.functions.v1beta2 import functions_pb2
          >>> api = cloud_functions_service_client.CloudFunctionsServiceClient()
          >>> location = api.location_path('[PROJECT]', '[LOCATION]')
          >>> function = functions_pb2.CloudFunction()
          >>> response = api.create_function(location, function)
          >>>
          >>> def callback(operation_future):
          >>>     # Handle result.
          >>>     result = operation_future.result()
          >>>
          >>> response.add_done_callback(callback)
          >>>
          >>> # Handle metadata.
          >>> metadata = response.metadata()

        Args:
          location (string): The project and location in which the function should be created, specified
            in the format ``projects/*/locations/*``
          function (:class:`google.cloud.proto.functions.v1beta2.functions_pb2.CloudFunction`): Function to be created.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax._OperationFuture` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = functions_pb2.CreateFunctionRequest(location=location,
                                                      function=function)
        return google.gax._OperationFuture(
            self._create_function(request, options), self.operations_client,
            functions_pb2.CloudFunction,
            operations_pb2.OperationMetadataV1Beta2, options)

    def update_function(self, name, function, options=None):
        """
        Updates existing function.

        Example:
          >>> from google.cloud.functions.v1beta2 import cloud_functions_service_client
          >>> from google.cloud.proto.functions.v1beta2 import functions_pb2
          >>> api = cloud_functions_service_client.CloudFunctionsServiceClient()
          >>> name = api.function_path('[PROJECT]', '[LOCATION]', '[FUNCTION]')
          >>> function = functions_pb2.CloudFunction()
          >>> response = api.update_function(name, function)
          >>>
          >>> def callback(operation_future):
          >>>     # Handle result.
          >>>     result = operation_future.result()
          >>>
          >>> response.add_done_callback(callback)
          >>>
          >>> # Handle metadata.
          >>> metadata = response.metadata()

        Args:
          name (string): The name of the function to be updated.
          function (:class:`google.cloud.proto.functions.v1beta2.functions_pb2.CloudFunction`): New version of the function.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax._OperationFuture` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = functions_pb2.UpdateFunctionRequest(name=name,
                                                      function=function)
        return google.gax._OperationFuture(
            self._update_function(request, options), self.operations_client,
            functions_pb2.CloudFunction,
            operations_pb2.OperationMetadataV1Beta2, options)

    def delete_function(self, name, options=None):
        """
        Deletes a function with the given name from the specified project. If the
        given function is used by some trigger, the trigger will be updated to
        remove this function.

        Example:
          >>> from google.cloud.functions.v1beta2 import cloud_functions_service_client
          >>> api = cloud_functions_service_client.CloudFunctionsServiceClient()
          >>> name = api.function_path('[PROJECT]', '[LOCATION]', '[FUNCTION]')
          >>> response = api.delete_function(name)
          >>>
          >>> def callback(operation_future):
          >>>     # Handle result.
          >>>     result = operation_future.result()
          >>>
          >>> response.add_done_callback(callback)
          >>>
          >>> # Handle metadata.
          >>> metadata = response.metadata()

        Args:
          name (string): The name of the function which should be deleted.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax._OperationFuture` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = functions_pb2.DeleteFunctionRequest(name=name)
        return google.gax._OperationFuture(
            self._delete_function(request, options), self.operations_client,
            empty_pb2.Empty, operations_pb2.OperationMetadataV1Beta2, options)

    def call_function(self, name, data, options=None):
        """
        Invokes synchronously deployed function. To be used for testing, very
        limited traffic allowed.

        Example:
          >>> from google.cloud.functions.v1beta2 import cloud_functions_service_client
          >>> api = cloud_functions_service_client.CloudFunctionsServiceClient()
          >>> name = api.function_path('[PROJECT]', '[LOCATION]', '[FUNCTION]')
          >>> data = ''
          >>> response = api.call_function(name, data)

        Args:
          name (string): The name of the function to be called.
          data (string): Input to be passed to the function.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.functions.v1beta2.functions_pb2.CallFunctionResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = functions_pb2.CallFunctionRequest(name=name, data=data)
        return self._call_function(request, options)
Exemple #16
0
class MetricsServiceV2Client(object):
    """Service for configuring logs-based metrics."""

    SERVICE_ADDRESS = 'logging.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _PAGE_DESCRIPTORS = {
        'list_log_metrics': _PageDesc('page_token', 'next_page_token',
                                      'metrics')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = (
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/cloud-platform.read-only',
        'https://www.googleapis.com/auth/logging.admin',
        'https://www.googleapis.com/auth/logging.read',
        'https://www.googleapis.com/auth/logging.write',
    )

    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')
    _METRIC_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/metrics/{metric}')

    @classmethod
    def project_path(cls, project):
        """Returns a fully-qualified project resource name string."""
        return cls._PROJECT_PATH_TEMPLATE.render({
            'project': project,
        })

    @classmethod
    def metric_path(cls, project, metric):
        """Returns a fully-qualified metric resource name string."""
        return cls._METRIC_PATH_TEMPLATE.render({
            'project': project,
            'metric': metric,
        })

    @classmethod
    def match_project_from_project_name(cls, project_name):
        """Parses the project from a project resource.

        Args:
          project_name (string): A fully-qualified path representing a project
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')

    @classmethod
    def match_project_from_metric_name(cls, metric_name):
        """Parses the project from a metric resource.

        Args:
          metric_name (string): A fully-qualified path representing a metric
            resource.

        Returns:
          A string representing the project.
        """
        return cls._METRIC_PATH_TEMPLATE.match(metric_name).get('project')

    @classmethod
    def match_metric_from_metric_name(cls, metric_name):
        """Parses the metric from a metric resource.

        Args:
          metric_name (string): A fully-qualified path representing a metric
            resource.

        Returns:
          A string representing the metric.
        """
        return cls._METRIC_PATH_TEMPLATE.match(metric_name).get('metric')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 credentials=None,
                 ssl_credentials=None,
                 scopes=None,
                 client_config=None,
                 app_name=None,
                 app_version='',
                 lib_name=None,
                 lib_version='',
                 metrics_headers=()):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          credentials (object): The authorization credentials to attach to
            requests. These credentials identify this application to the
            service.
          ssl_credentials (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          scopes (list[string]): A list of OAuth2 scopes to attach to requests.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          app_name (string): The name of the application calling
            the service. Recommended for analytics purposes.
          app_version (string): The version of the application calling
            the service. Recommended for analytics purposes.
          lib_name (string): The API library software used for calling
            the service. (Unless you are writing an API client itself,
            leave this as default.)
          lib_version (string): The API library software version used
            for calling the service. (Unless you are writing an API client
            itself, leave this as default.)
          metrics_headers (dict): A dictionary of values for tracking
            client library metrics. Ultimately serializes to a string
            (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be
            considered private.

        Returns:
          A MetricsServiceV2Client object.
        """
        # Unless the calling application specifically requested
        # OAuth scopes, request everything.
        if scopes is None:
            scopes = self._ALL_SCOPES

        # Initialize an empty client config, if none is set.
        if client_config is None:
            client_config = {}

        # Initialize metrics_headers as an ordered dictionary
        # (cuts down on cardinality of the resulting string slightly).
        metrics_headers = collections.OrderedDict(metrics_headers)
        metrics_headers['gl-python'] = platform.python_version()

        # The library may or may not be set, depending on what is
        # calling this client. Newer client libraries set the library name
        # and version.
        if lib_name:
            metrics_headers[lib_name] = lib_version

        # Finally, track the GAPIC package version.
        metrics_headers['gapic'] = pkg_resources.get_distribution(
            'gapic-google-cloud-logging-v2', ).version

        # Load the configuration defaults.
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'metrics_service_v2_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.logging.v2.MetricsServiceV2',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            metrics_headers=metrics_headers,
            page_descriptors=self._PAGE_DESCRIPTORS,
        )
        self.metrics_service_v2_stub = config.create_stub(
            logging_metrics_pb2.MetricsServiceV2Stub,
            channel=channel,
            service_path=service_path,
            service_port=port,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)

        self._list_log_metrics = api_callable.create_api_call(
            self.metrics_service_v2_stub.ListLogMetrics,
            settings=defaults['list_log_metrics'])
        self._get_log_metric = api_callable.create_api_call(
            self.metrics_service_v2_stub.GetLogMetric,
            settings=defaults['get_log_metric'])
        self._create_log_metric = api_callable.create_api_call(
            self.metrics_service_v2_stub.CreateLogMetric,
            settings=defaults['create_log_metric'])
        self._update_log_metric = api_callable.create_api_call(
            self.metrics_service_v2_stub.UpdateLogMetric,
            settings=defaults['update_log_metric'])
        self._delete_log_metric = api_callable.create_api_call(
            self.metrics_service_v2_stub.DeleteLogMetric,
            settings=defaults['delete_log_metric'])

    # Service calls
    def list_log_metrics(self, parent, page_size=None, options=None):
        """
        Lists logs-based metrics.

        Example:
          >>> from google.cloud.gapic.logging.v2 import metrics_service_v2_client
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> client = metrics_service_v2_client.MetricsServiceV2Client()
          >>> parent = client.project_path('[PROJECT]')
          >>>
          >>> # Iterate over all results
          >>> for element in client.list_log_metrics(parent):
          >>>     # process element
          >>>     pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in client.list_log_metrics(parent, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>     for element in page:
          >>>         # process element
          >>>         pass

        Args:
          parent (string): Required. The name of the project containing the metrics:

            ::

                \"projects/[PROJECT_ID]\"
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.cloud.proto.logging.v2.logging_metrics_pb2.LogMetric` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = logging_metrics_pb2.ListLogMetricsRequest(
            parent=parent, page_size=page_size)
        return self._list_log_metrics(request, options)

    def get_log_metric(self, metric_name, options=None):
        """
        Gets a logs-based metric.

        Example:
          >>> from google.cloud.gapic.logging.v2 import metrics_service_v2_client
          >>> client = metrics_service_v2_client.MetricsServiceV2Client()
          >>> metric_name = client.metric_path('[PROJECT]', '[METRIC]')
          >>> response = client.get_log_metric(metric_name)

        Args:
          metric_name (string): The resource name of the desired metric:

            ::

                \"projects/[PROJECT_ID]/metrics/[METRIC_ID]\"
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.logging.v2.logging_metrics_pb2.LogMetric` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = logging_metrics_pb2.GetLogMetricRequest(
            metric_name=metric_name)
        return self._get_log_metric(request, options)

    def create_log_metric(self, parent, metric, options=None):
        """
        Creates a logs-based metric.

        Example:
          >>> from google.cloud.gapic.logging.v2 import metrics_service_v2_client
          >>> from google.cloud.proto.logging.v2 import logging_metrics_pb2
          >>> client = metrics_service_v2_client.MetricsServiceV2Client()
          >>> parent = client.project_path('[PROJECT]')
          >>> metric = logging_metrics_pb2.LogMetric()
          >>> response = client.create_log_metric(parent, metric)

        Args:
          parent (string): The resource name of the project in which to create the metric:

            ::

                \"projects/[PROJECT_ID]\"

            The new metric must be provided in the request.
          metric (:class:`google.cloud.proto.logging.v2.logging_metrics_pb2.LogMetric`): The new logs-based metric, which must not have an identifier that
            already exists.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.logging.v2.logging_metrics_pb2.LogMetric` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = logging_metrics_pb2.CreateLogMetricRequest(parent=parent,
                                                             metric=metric)
        return self._create_log_metric(request, options)

    def update_log_metric(self, metric_name, metric, options=None):
        """
        Creates or updates a logs-based metric.

        Example:
          >>> from google.cloud.gapic.logging.v2 import metrics_service_v2_client
          >>> from google.cloud.proto.logging.v2 import logging_metrics_pb2
          >>> client = metrics_service_v2_client.MetricsServiceV2Client()
          >>> metric_name = client.metric_path('[PROJECT]', '[METRIC]')
          >>> metric = logging_metrics_pb2.LogMetric()
          >>> response = client.update_log_metric(metric_name, metric)

        Args:
          metric_name (string): The resource name of the metric to update:

            ::

                \"projects/[PROJECT_ID]/metrics/[METRIC_ID]\"

            The updated metric must be provided in the request and it's
            ``name`` field must be the same as ``[METRIC_ID]`` If the metric
            does not exist in ``[PROJECT_ID]``, then a new metric is created.
          metric (:class:`google.cloud.proto.logging.v2.logging_metrics_pb2.LogMetric`): The updated metric.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.logging.v2.logging_metrics_pb2.LogMetric` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = logging_metrics_pb2.UpdateLogMetricRequest(
            metric_name=metric_name, metric=metric)
        return self._update_log_metric(request, options)

    def delete_log_metric(self, metric_name, options=None):
        """
        Deletes a logs-based metric.

        Example:
          >>> from google.cloud.gapic.logging.v2 import metrics_service_v2_client
          >>> client = metrics_service_v2_client.MetricsServiceV2Client()
          >>> metric_name = client.metric_path('[PROJECT]', '[METRIC]')
          >>> client.delete_log_metric(metric_name)

        Args:
          metric_name (string): The resource name of the metric to delete:

            ::

                \"projects/[PROJECT_ID]/metrics/[METRIC_ID]\"
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = logging_metrics_pb2.DeleteLogMetricRequest(
            metric_name=metric_name)
        self._delete_log_metric(request, options)
class ErrorGroupServiceApi(object):
    """Service for retrieving and updating individual error groups."""

    SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _CODE_GEN_NAME_VERSION = 'gapic/0.1.0'

    _GAX_VERSION = pkg_resources.get_distribution('google-gax').version

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = ('https://www.googleapis.com/auth/cloud-platform', )

    _GROUP_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/groups/{group}')

    @classmethod
    def group_path(cls, project, group):
        """Returns a fully-qualified group resource name string."""
        return cls._GROUP_PATH_TEMPLATE.render({
            'project': project,
            'group': group,
        })

    @classmethod
    def match_project_from_group_name(cls, group_name):
        """Parses the project from a group resource.

        Args:
          group_name (string): A fully-qualified path representing a group
            resource.

        Returns:
          A string representing the project.
        """
        return cls._GROUP_PATH_TEMPLATE.match(group_name).get('project')

    @classmethod
    def match_group_from_group_name(cls, group_name):
        """Parses the group from a group resource.

        Args:
          group_name (string): A fully-qualified path representing a group
            resource.

        Returns:
          A string representing the group.
        """
        return cls._GROUP_PATH_TEMPLATE.match(group_name).get('group')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 metadata_transformer=None,
                 ssl_creds=None,
                 scopes=None,
                 client_config=None,
                 app_name='gax',
                 app_version=_GAX_VERSION):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          ssl_creds (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          metadata_transformer (Callable[[], list]): A function that creates
             the metadata for requests.
          app_name (string): The codename of the calling service.
          app_version (string): The version of the calling service.

        Returns:
          A ErrorGroupServiceApi object.
        """
        if scopes is None:
            scopes = self._ALL_SCOPES
        if client_config is None:
            client_config = {}
        goog_api_client = '{}/{} {} gax/{} python/{}'.format(
            app_name, app_version, self._CODE_GEN_NAME_VERSION,
            self._GAX_VERSION, platform.python_version())
        metadata = [('x-goog-api-client', goog_api_client)]
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'error_group_service_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.devtools.clouderrorreporting.v1beta1.ErrorGroupService',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            kwargs={'metadata': metadata})
        self.error_group_service_stub = config.create_stub(
            error_group_service_pb2.ErrorGroupServiceStub,
            service_path,
            port,
            ssl_creds=ssl_creds,
            channel=channel,
            metadata_transformer=metadata_transformer,
            scopes=scopes)

        self._get_group = api_callable.create_api_call(
            self.error_group_service_stub.GetGroup,
            settings=defaults['get_group'])
        self._update_group = api_callable.create_api_call(
            self.error_group_service_stub.UpdateGroup,
            settings=defaults['update_group'])

    # Service calls
    def get_group(self, group_name, options=None):
        """
        Get the specified group.

        Example:
          >>> from google.cloud.gapic.errorreporting.v1beta1 import error_group_service_api
          >>> api = error_group_service_api.ErrorGroupServiceApi()
          >>> group_name = api.group_path('[PROJECT]', '[GROUP]')
          >>> response = api.get_group(group_name)

        Args:
          group_name (string): [Required] The group resource name. Written as
            <code>projects/<var>projectID</var>/groups/<var>group_name</var></code>.
            Call
            <a href=\"/error-reporting/reference/rest/v1beta1/projects.groupStats/list\">
            <code>groupStats.list</code></a> to return a list of groups belonging to
            this project.

            Example: <code>projects/my-project-123/groups/my-group</code>
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.devtools.clouderrorreporting.v1beta1.common_pb2.ErrorGroup` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = error_group_service_pb2.GetGroupRequest(
            group_name=group_name)
        return self._get_group(request, options)

    def update_group(self, group, options=None):
        """
        Replace the data for the specified group.
        Fails if the group does not exist.

        Example:
          >>> from google.cloud.gapic.errorreporting.v1beta1 import error_group_service_api
          >>> from google.devtools.clouderrorreporting.v1beta1 import common_pb2
          >>> api = error_group_service_api.ErrorGroupServiceApi()
          >>> group = common_pb2.ErrorGroup()
          >>> response = api.update_group(group)

        Args:
          group (:class:`google.devtools.clouderrorreporting.v1beta1.common_pb2.ErrorGroup`): [Required] The group which replaces the resource on the server.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.devtools.clouderrorreporting.v1beta1.common_pb2.ErrorGroup` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = error_group_service_pb2.UpdateGroupRequest(group=group)
        return self._update_group(request, options)
class OperationsApi(object):
    """
    Manages long-running operations with an API service.

    When an API method normally takes long time to complete, it can be designed
    to return ``Operation`` to the client, and the client can use this
    interface to receive the real response asynchronously by polling the
    operation resource, or pass the operation resource to another API (such as
    Google Cloud Pub/Sub API) to receive the response.  Any API service that
    returns long-running operations should implement the ``Operations`` interface
    so developers can have a consistent client experience.
    """

    SERVICE_ADDRESS = 'longrunning.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _CODE_GEN_NAME_VERSION = 'gapic/0.1.0'

    _GAX_VERSION = pkg_resources.get_distribution('google-gax').version

    _PAGE_DESCRIPTORS = {
        'list_operations': _PageDesc('page_token', 'next_page_token',
                                     'operations')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = ()

    _OPERATION_PATH_PATH_TEMPLATE = path_template.PathTemplate(
        'operations/{operation_path=**}')

    @classmethod
    def operation_path_path(cls, operation_path):
        """Returns a fully-qualified operation_path resource name string."""
        return cls._OPERATION_PATH_PATH_TEMPLATE.render({
            'operation_path': operation_path,
        })

    @classmethod
    def match_operation_path_from_operation_path_name(cls,
                                                      operation_path_name):
        """Parses the operation_path from a operation_path resource.

        Args:
          operation_path_name (string): A fully-qualified path representing a operation_path
            resource.

        Returns:
          A string representing the operation_path.
        """
        return cls._OPERATION_PATH_PATH_TEMPLATE.match(
            operation_path_name).get('operation_path')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 metadata_transformer=None,
                 ssl_creds=None,
                 scopes=None,
                 client_config=None,
                 app_name='gax',
                 app_version=_GAX_VERSION):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          ssl_creds (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          metadata_transformer (Callable[[], list]): A function that creates
             the metadata for requests.
          app_name (string): The codename of the calling service.
          app_version (string): The version of the calling service.

        Returns:
          A OperationsApi object.
        """
        if scopes is None:
            scopes = self._ALL_SCOPES
        if client_config is None:
            client_config = {}
        goog_api_client = '{}/{} {} gax/{} python/{}'.format(
            app_name, app_version, self._CODE_GEN_NAME_VERSION,
            self._GAX_VERSION, platform.python_version())
        metadata = [('x-goog-api-client', goog_api_client)]
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'operations_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.longrunning.Operations',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            kwargs={'metadata': metadata},
            page_descriptors=self._PAGE_DESCRIPTORS)
        self.operations_stub = config.create_stub(
            operations_pb2.OperationsStub,
            service_path,
            port,
            ssl_creds=ssl_creds,
            channel=channel,
            metadata_transformer=metadata_transformer,
            scopes=scopes)

        self._get_operation = api_callable.create_api_call(
            self.operations_stub.GetOperation,
            settings=defaults['get_operation'])
        self._list_operations = api_callable.create_api_call(
            self.operations_stub.ListOperations,
            settings=defaults['list_operations'])
        self._cancel_operation = api_callable.create_api_call(
            self.operations_stub.CancelOperation,
            settings=defaults['cancel_operation'])
        self._delete_operation = api_callable.create_api_call(
            self.operations_stub.DeleteOperation,
            settings=defaults['delete_operation'])

    # Service calls
    def get_operation(self, name, options=None):
        """
        Gets the latest state of a long-running operation.  Clients can use this
        method to poll the operation result at intervals as recommended by the API
        service.

        Example:
          >>> from google.cloud.gapic.longrunning import operations_api
          >>> api = operations_api.OperationsApi()
          >>> name = api.operation_path_path('[OPERATION_PATH]')
          >>> response = api.get_operation(name)

        Args:
          name (string): The name of the operation resource.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.longrunning.operations_pb2.Operation` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = operations_pb2.GetOperationRequest(name=name)
        return self._get_operation(request, options)

    def list_operations(self, name, filter_, page_size=0, options=None):
        """
        Lists operations that match the specified filter in the request. If the
        server doesn't support this method, it returns ``UNIMPLEMENTED``.
        NOTE: the ``name`` binding below allows API services to override the binding
        to use different resource name schemes, such as ``users/*/operations``.

        Example:
          >>> from google.cloud.gapic.longrunning import operations_api
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = operations_api.OperationsApi()
          >>> name = ''
          >>> filter_ = ''
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_operations(name, filter_):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_operations(name, filter_, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          name (string): The name of the operation collection.
          filter_ (string): The standard list filter.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.longrunning.operations_pb2.Operation` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = operations_pb2.ListOperationsRequest(
            name=name, filter=filter_, page_size=page_size)
        return self._list_operations(request, options)

    def cancel_operation(self, name, options=None):
        """
        Starts asynchronous cancellation on a long-running operation.  The server
        makes a best effort to cancel the operation, but success is not
        guaranteed.  If the server doesn't support this method, it returns
        ``google.rpc.Code.UNIMPLEMENTED``.  Clients can use
        ``Operations.GetOperation`` or
        other methods to check whether the cancellation succeeded or whether the
        operation completed despite cancellation.

        Example:
          >>> from google.cloud.gapic.longrunning import operations_api
          >>> api = operations_api.OperationsApi()
          >>> name = api.operation_path_path('[OPERATION_PATH]')
          >>> api.cancel_operation(name)

        Args:
          name (string): The name of the operation resource to be cancelled.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = operations_pb2.CancelOperationRequest(name=name)
        self._cancel_operation(request, options)

    def delete_operation(self, name, options=None):
        """
        Deletes a long-running operation. This method indicates that the client is
        no longer interested in the operation result. It does not cancel the
        operation. If the server doesn't support this method, it returns
        ``google.rpc.Code.UNIMPLEMENTED``.

        Example:
          >>> from google.cloud.gapic.longrunning import operations_api
          >>> api = operations_api.OperationsApi()
          >>> name = api.operation_path_path('[OPERATION_PATH]')
          >>> api.delete_operation(name)

        Args:
          name (string): The name of the operation resource to be deleted.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = operations_pb2.DeleteOperationRequest(name=name)
        self._delete_operation(request, options)
Exemple #19
0
class DatabaseAdminClient(object):
    """
    Cloud Spanner Database Admin API

    The Cloud Spanner Database Admin API can be used to create, drop, and
    list databases. It also enables updating the schema of pre-existing
    databases.
    """

    SERVICE_ADDRESS = 'spanner.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _PAGE_DESCRIPTORS = {
        'list_databases': _PageDesc('page_token', 'next_page_token',
                                    'databases')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = (
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/spanner.admin',
    )

    _INSTANCE_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/instances/{instance}')
    _DATABASE_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/instances/{instance}/databases/{database}')

    @classmethod
    def instance_path(cls, project, instance):
        """Returns a fully-qualified instance resource name string."""
        return cls._INSTANCE_PATH_TEMPLATE.render({
            'project': project,
            'instance': instance,
        })

    @classmethod
    def database_path(cls, project, instance, database):
        """Returns a fully-qualified database resource name string."""
        return cls._DATABASE_PATH_TEMPLATE.render({
            'project': project,
            'instance': instance,
            'database': database,
        })

    @classmethod
    def match_project_from_instance_name(cls, instance_name):
        """Parses the project from a instance resource.

        Args:
            instance_name (str): A fully-qualified path representing a instance
                resource.

        Returns:
            A string representing the project.
        """
        return cls._INSTANCE_PATH_TEMPLATE.match(instance_name).get('project')

    @classmethod
    def match_instance_from_instance_name(cls, instance_name):
        """Parses the instance from a instance resource.

        Args:
            instance_name (str): A fully-qualified path representing a instance
                resource.

        Returns:
            A string representing the instance.
        """
        return cls._INSTANCE_PATH_TEMPLATE.match(instance_name).get('instance')

    @classmethod
    def match_project_from_database_name(cls, database_name):
        """Parses the project from a database resource.

        Args:
            database_name (str): A fully-qualified path representing a database
                resource.

        Returns:
            A string representing the project.
        """
        return cls._DATABASE_PATH_TEMPLATE.match(database_name).get('project')

    @classmethod
    def match_instance_from_database_name(cls, database_name):
        """Parses the instance from a database resource.

        Args:
            database_name (str): A fully-qualified path representing a database
                resource.

        Returns:
            A string representing the instance.
        """
        return cls._DATABASE_PATH_TEMPLATE.match(database_name).get('instance')

    @classmethod
    def match_database_from_database_name(cls, database_name):
        """Parses the database from a database resource.

        Args:
            database_name (str): A fully-qualified path representing a database
                resource.

        Returns:
            A string representing the database.
        """
        return cls._DATABASE_PATH_TEMPLATE.match(database_name).get('database')

    def __init__(self,
                 channel=None,
                 credentials=None,
                 ssl_credentials=None,
                 scopes=None,
                 client_config=None,
                 lib_name=None,
                 lib_version='',
                 metrics_headers=()):
        """Constructor.

        Args:
            channel (~grpc.Channel): A ``Channel`` instance through
                which to make calls.
            credentials (~google.auth.credentials.Credentials): The authorization
                credentials to attach to requests. These credentials identify this
                application to the service.
            ssl_credentials (~grpc.ChannelCredentials): A
                ``ChannelCredentials`` instance for use with an SSL-enabled
                channel.
            scopes (Sequence[str]): A list of OAuth2 scopes to attach to requests.
            client_config (dict):
                A dictionary for call options for each method. See
                :func:`google.gax.construct_settings` for the structure of
                this data. Falls back to the default config if not specified
                or the specified config is missing data points.
            lib_name (str): The API library software used for calling
                the service. (Unless you are writing an API client itself,
                leave this as default.)
            lib_version (str): The API library software version used
                for calling the service. (Unless you are writing an API client
                itself, leave this as default.)
            metrics_headers (dict): A dictionary of values for tracking
                client library metrics. Ultimately serializes to a string
                (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be
                considered private.
        """
        # Unless the calling application specifically requested
        # OAuth scopes, request everything.
        if scopes is None:
            scopes = self._ALL_SCOPES

        # Initialize an empty client config, if none is set.
        if client_config is None:
            client_config = {}

        # Initialize metrics_headers as an ordered dictionary
        # (cuts down on cardinality of the resulting string slightly).
        metrics_headers = collections.OrderedDict(metrics_headers)
        metrics_headers['gl-python'] = platform.python_version()

        # The library may or may not be set, depending on what is
        # calling this client. Newer client libraries set the library name
        # and version.
        if lib_name:
            metrics_headers[lib_name] = lib_version

        # Finally, track the GAPIC package version.
        metrics_headers['gapic'] = pkg_resources.get_distribution(
            'google-cloud-spanner', ).version

        # Load the configuration defaults.
        defaults = api_callable.construct_settings(
            'google.spanner.admin.database.v1.DatabaseAdmin',
            database_admin_client_config.config,
            client_config,
            config.STATUS_CODE_NAMES,
            metrics_headers=metrics_headers,
            page_descriptors=self._PAGE_DESCRIPTORS,
        )
        self.database_admin_stub = config.create_stub(
            spanner_database_admin_pb2.DatabaseAdminStub,
            channel=channel,
            service_path=self.SERVICE_ADDRESS,
            service_port=self.DEFAULT_SERVICE_PORT,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)

        self.operations_client = operations_client.OperationsClient(
            service_path=self.SERVICE_ADDRESS,
            channel=channel,
            credentials=credentials,
            ssl_credentials=ssl_credentials,
            scopes=scopes,
            client_config=client_config,
            metrics_headers=metrics_headers,
        )

        self._list_databases = api_callable.create_api_call(
            self.database_admin_stub.ListDatabases,
            settings=defaults['list_databases'])
        self._create_database = api_callable.create_api_call(
            self.database_admin_stub.CreateDatabase,
            settings=defaults['create_database'])
        self._get_database = api_callable.create_api_call(
            self.database_admin_stub.GetDatabase,
            settings=defaults['get_database'])
        self._update_database_ddl = api_callable.create_api_call(
            self.database_admin_stub.UpdateDatabaseDdl,
            settings=defaults['update_database_ddl'])
        self._drop_database = api_callable.create_api_call(
            self.database_admin_stub.DropDatabase,
            settings=defaults['drop_database'])
        self._get_database_ddl = api_callable.create_api_call(
            self.database_admin_stub.GetDatabaseDdl,
            settings=defaults['get_database_ddl'])
        self._set_iam_policy = api_callable.create_api_call(
            self.database_admin_stub.SetIamPolicy,
            settings=defaults['set_iam_policy'])
        self._get_iam_policy = api_callable.create_api_call(
            self.database_admin_stub.GetIamPolicy,
            settings=defaults['get_iam_policy'])
        self._test_iam_permissions = api_callable.create_api_call(
            self.database_admin_stub.TestIamPermissions,
            settings=defaults['test_iam_permissions'])

    # Service calls
    def list_databases(self, parent, page_size=None, options=None):
        """
        Lists Cloud Spanner databases.

        Example:
            >>> from google.cloud import spanner_admin_database_v1
            >>> from google.gax import CallOptions, INITIAL_PAGE
            >>>
            >>> client = spanner_admin_database_v1.DatabaseAdminClient()
            >>>
            >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]')
            >>>
            >>>
            >>> # Iterate over all results
            >>> for element in client.list_databases(parent):
            ...     # process element
            ...     pass
            >>>
            >>> # Or iterate over results one page at a time
            >>> for page in client.list_databases(parent, options=CallOptions(page_token=INITIAL_PAGE)):
            ...     for element in page:
            ...         # process element
            ...         pass

        Args:
            parent (str): Required. The instance whose databases should be listed.
                Values are of the form ``projects/<project>/instances/<instance>``.
            page_size (int): The maximum number of resources contained in the
                underlying API response. If page streaming is performed per-
                resource, this parameter does not affect the return value. If page
                streaming is performed per-page, this determines the maximum number
                of resources in a page.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.gax.PageIterator` instance. By default, this
            is an iterable of :class:`~google.cloud.spanner_admin_database_v1.types.Database` instances.
            This object can also be configured to iterate over the pages
            of the response through the `options` parameter.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_database_admin_pb2.ListDatabasesRequest(
            parent=parent, page_size=page_size)
        return self._list_databases(request, options)

    def create_database(self,
                        parent,
                        create_statement,
                        extra_statements=None,
                        options=None):
        """
        Creates a new Cloud Spanner database and starts to prepare it for serving.
        The returned ``long-running operation`` will
        have a name of the format ``<database_name>/operations/<operation_id>`` and
        can be used to track preparation of the database. The
        ``metadata`` field type is
        ``CreateDatabaseMetadata``. The
        ``response`` field type is
        ``Database``, if successful.

        Example:
            >>> from google.cloud import spanner_admin_database_v1
            >>>
            >>> client = spanner_admin_database_v1.DatabaseAdminClient()
            >>>
            >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]')
            >>> create_statement = ''
            >>>
            >>> response = client.create_database(parent, create_statement)
            >>>
            >>> def callback(operation_future):
            ...     # Handle result.
            ...     result = operation_future.result()
            >>>
            >>> response.add_done_callback(callback)
            >>>
            >>> # Handle metadata.
            >>> metadata = response.metadata()

        Args:
            parent (str): Required. The name of the instance that will serve the new database.
                Values are of the form ``projects/<project>/instances/<instance>``.
            create_statement (str): Required. A ``CREATE DATABASE`` statement, which specifies the ID of the
                new database.  The database ID must conform to the regular expression
                ``[a-z][a-z0-9_\-]*[a-z0-9]`` and be between 2 and 30 characters in length.
            extra_statements (list[str]): An optional list of DDL statements to run inside the newly created
                database. Statements can create tables, indexes, etc. These
                statements execute atomically with the creation of the database:
                if there is an error in any statement, the database is not created.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_admin_database_v1.types._OperationFuture` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_database_admin_pb2.CreateDatabaseRequest(
            parent=parent,
            create_statement=create_statement,
            extra_statements=extra_statements)
        return google.gax._OperationFuture(
            self._create_database(request, options), self.operations_client,
            spanner_database_admin_pb2.Database,
            spanner_database_admin_pb2.CreateDatabaseMetadata, options)

    def get_database(self, name, options=None):
        """
        Gets the state of a Cloud Spanner database.

        Example:
            >>> from google.cloud import spanner_admin_database_v1
            >>>
            >>> client = spanner_admin_database_v1.DatabaseAdminClient()
            >>>
            >>> name = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]')
            >>>
            >>> response = client.get_database(name)

        Args:
            name (str): Required. The name of the requested database. Values are of the form
                ``projects/<project>/instances/<instance>/databases/<database>``.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_admin_database_v1.types.Database` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_database_admin_pb2.GetDatabaseRequest(name=name)
        return self._get_database(request, options)

    def update_database_ddl(self,
                            database,
                            statements,
                            operation_id=None,
                            options=None):
        """
        Updates the schema of a Cloud Spanner database by
        creating/altering/dropping tables, columns, indexes, etc. The returned
        ``long-running operation`` will have a name of
        the format ``<database_name>/operations/<operation_id>`` and can be used to
        track execution of the schema change(s). The
        ``metadata`` field type is
        ``UpdateDatabaseDdlMetadata``.  The operation has no response.

        Example:
            >>> from google.cloud import spanner_admin_database_v1
            >>>
            >>> client = spanner_admin_database_v1.DatabaseAdminClient()
            >>>
            >>> database = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]')
            >>> statements = []
            >>>
            >>> response = client.update_database_ddl(database, statements)
            >>>
            >>> def callback(operation_future):
            ...     # Handle result.
            ...     result = operation_future.result()
            >>>
            >>> response.add_done_callback(callback)
            >>>
            >>> # Handle metadata.
            >>> metadata = response.metadata()

        Args:
            database (str): Required. The database to update.
            statements (list[str]): DDL statements to be applied to the database.
            operation_id (str): If empty, the new update request is assigned an
                automatically-generated operation ID. Otherwise, ``operation_id``
                is used to construct the name of the resulting
                ``Operation``.

                Specifying an explicit operation ID simplifies determining
                whether the statements were executed in the event that the
                ``UpdateDatabaseDdl`` call is replayed,
                or the return value is otherwise lost: the ``database`` and
                ``operation_id`` fields can be combined to form the
                ``name`` of the resulting
                ``longrunning.Operation``: ``<database>/operations/<operation_id>``.

                ``operation_id`` should be unique within the database, and must be
                a valid identifier: ``[a-z][a-z0-9_]*``. Note that
                automatically-generated operation IDs always begin with an
                underscore. If the named operation already exists,
                ``UpdateDatabaseDdl`` returns
                ``ALREADY_EXISTS``.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_admin_database_v1.types._OperationFuture` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_database_admin_pb2.UpdateDatabaseDdlRequest(
            database=database,
            statements=statements,
            operation_id=operation_id)
        return google.gax._OperationFuture(
            self._update_database_ddl(request, options),
            self.operations_client, empty_pb2.Empty,
            spanner_database_admin_pb2.UpdateDatabaseDdlMetadata, options)

    def drop_database(self, database, options=None):
        """
        Drops (aka deletes) a Cloud Spanner database.

        Example:
            >>> from google.cloud import spanner_admin_database_v1
            >>>
            >>> client = spanner_admin_database_v1.DatabaseAdminClient()
            >>>
            >>> database = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]')
            >>>
            >>> client.drop_database(database)

        Args:
            database (str): Required. The database to be dropped.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_database_admin_pb2.DropDatabaseRequest(
            database=database)
        self._drop_database(request, options)

    def get_database_ddl(self, database, options=None):
        """
        Returns the schema of a Cloud Spanner database as a list of formatted
        DDL statements. This method does not show pending schema updates, those may
        be queried using the ``Operations`` API.

        Example:
            >>> from google.cloud import spanner_admin_database_v1
            >>>
            >>> client = spanner_admin_database_v1.DatabaseAdminClient()
            >>>
            >>> database = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]')
            >>>
            >>> response = client.get_database_ddl(database)

        Args:
            database (str): Required. The database whose schema we wish to get.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_admin_database_v1.types.GetDatabaseDdlResponse` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_database_admin_pb2.GetDatabaseDdlRequest(
            database=database)
        return self._get_database_ddl(request, options)

    def set_iam_policy(self, resource, policy, options=None):
        """
        Sets the access control policy on a database resource. Replaces any
        existing policy.

        Authorization requires ``spanner.databases.setIamPolicy`` permission on
        ``resource``.

        Example:
            >>> from google.cloud import spanner_admin_database_v1
            >>>
            >>> client = spanner_admin_database_v1.DatabaseAdminClient()
            >>>
            >>> resource = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]')
            >>> policy = {}
            >>>
            >>> response = client.set_iam_policy(resource, policy)

        Args:
            resource (str): REQUIRED: The resource for which the policy is being specified.
                ``resource`` is usually specified as a path. For example, a Project
                resource is specified as ``projects/{project}``.
            policy (Union[dict, ~google.cloud.spanner_admin_database_v1.types.Policy]): REQUIRED: The complete policy to be applied to the ``resource``. The size of
                the policy is limited to a few 10s of KB. An empty policy is a
                valid policy but certain Cloud Platform services (such as Projects)
                might reject them.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_admin_database_v1.types.Policy`
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_admin_database_v1.types.Policy` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_policy_pb2.SetIamPolicyRequest(resource=resource,
                                                     policy=policy)
        return self._set_iam_policy(request, options)

    def get_iam_policy(self, resource, options=None):
        """
        Gets the access control policy for a database resource. Returns an empty
        policy if a database exists but does not have a policy set.

        Authorization requires ``spanner.databases.getIamPolicy`` permission on
        ``resource``.

        Example:
            >>> from google.cloud import spanner_admin_database_v1
            >>>
            >>> client = spanner_admin_database_v1.DatabaseAdminClient()
            >>>
            >>> resource = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]')
            >>>
            >>> response = client.get_iam_policy(resource)

        Args:
            resource (str): REQUIRED: The resource for which the policy is being requested.
                ``resource`` is usually specified as a path. For example, a Project
                resource is specified as ``projects/{project}``.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_admin_database_v1.types.Policy` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_policy_pb2.GetIamPolicyRequest(resource=resource)
        return self._get_iam_policy(request, options)

    def test_iam_permissions(self, resource, permissions, options=None):
        """
        Returns permissions that the caller has on the specified database resource.

        Attempting this RPC on a non-existent Cloud Spanner database will result in
        a NOT_FOUND error if the user has ``spanner.databases.list`` permission on
        the containing Cloud Spanner instance. Otherwise returns an empty set of
        permissions.

        Example:
            >>> from google.cloud import spanner_admin_database_v1
            >>>
            >>> client = spanner_admin_database_v1.DatabaseAdminClient()
            >>>
            >>> resource = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]')
            >>> permissions = []
            >>>
            >>> response = client.test_iam_permissions(resource, permissions)

        Args:
            resource (str): REQUIRED: The resource for which the policy detail is being requested.
                ``resource`` is usually specified as a path. For example, a Project
                resource is specified as ``projects/{project}``.
            permissions (list[str]): The set of permissions to check for the ``resource``. Permissions with
                wildcards (such as '*' or 'storage.*') are not allowed. For more
                information see
                `IAM Overview <https://cloud.google.com/iam/docs/overview#permissions>`_.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_admin_database_v1.types.TestIamPermissionsResponse` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = iam_policy_pb2.TestIamPermissionsRequest(
            resource=resource, permissions=permissions)
        return self._test_iam_permissions(request, options)
Exemple #20
0
class SpannerClient(object):
    """
    Cloud Spanner API

    The Cloud Spanner API can be used to manage sessions and execute
    transactions on data stored in Cloud Spanner databases.
    """

    SERVICE_ADDRESS = 'spanner.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = (
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/spanner.data', )

    _DATABASE_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/instances/{instance}/databases/{database}')
    _SESSION_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/instances/{instance}/databases/{database}/sessions/{session}'
    )

    @classmethod
    def database_path(cls, project, instance, database):
        """Returns a fully-qualified database resource name string."""
        return cls._DATABASE_PATH_TEMPLATE.render({
            'project': project,
            'instance': instance,
            'database': database,
        })

    @classmethod
    def session_path(cls, project, instance, database, session):
        """Returns a fully-qualified session resource name string."""
        return cls._SESSION_PATH_TEMPLATE.render({
            'project': project,
            'instance': instance,
            'database': database,
            'session': session,
        })

    @classmethod
    def match_project_from_database_name(cls, database_name):
        """Parses the project from a database resource.

        Args:
            database_name (str): A fully-qualified path representing a database
                resource.

        Returns:
            A string representing the project.
        """
        return cls._DATABASE_PATH_TEMPLATE.match(database_name).get('project')

    @classmethod
    def match_instance_from_database_name(cls, database_name):
        """Parses the instance from a database resource.

        Args:
            database_name (str): A fully-qualified path representing a database
                resource.

        Returns:
            A string representing the instance.
        """
        return cls._DATABASE_PATH_TEMPLATE.match(database_name).get('instance')

    @classmethod
    def match_database_from_database_name(cls, database_name):
        """Parses the database from a database resource.

        Args:
            database_name (str): A fully-qualified path representing a database
                resource.

        Returns:
            A string representing the database.
        """
        return cls._DATABASE_PATH_TEMPLATE.match(database_name).get('database')

    @classmethod
    def match_project_from_session_name(cls, session_name):
        """Parses the project from a session resource.

        Args:
            session_name (str): A fully-qualified path representing a session
                resource.

        Returns:
            A string representing the project.
        """
        return cls._SESSION_PATH_TEMPLATE.match(session_name).get('project')

    @classmethod
    def match_instance_from_session_name(cls, session_name):
        """Parses the instance from a session resource.

        Args:
            session_name (str): A fully-qualified path representing a session
                resource.

        Returns:
            A string representing the instance.
        """
        return cls._SESSION_PATH_TEMPLATE.match(session_name).get('instance')

    @classmethod
    def match_database_from_session_name(cls, session_name):
        """Parses the database from a session resource.

        Args:
            session_name (str): A fully-qualified path representing a session
                resource.

        Returns:
            A string representing the database.
        """
        return cls._SESSION_PATH_TEMPLATE.match(session_name).get('database')

    @classmethod
    def match_session_from_session_name(cls, session_name):
        """Parses the session from a session resource.

        Args:
            session_name (str): A fully-qualified path representing a session
                resource.

        Returns:
            A string representing the session.
        """
        return cls._SESSION_PATH_TEMPLATE.match(session_name).get('session')

    def __init__(self,
                 channel=None,
                 credentials=None,
                 ssl_credentials=None,
                 scopes=None,
                 client_config=None,
                 lib_name=None,
                 lib_version='',
                 metrics_headers=()):
        """Constructor.

        Args:
            channel (~grpc.Channel): A ``Channel`` instance through
                which to make calls.
            credentials (~google.auth.credentials.Credentials): The authorization
                credentials to attach to requests. These credentials identify this
                application to the service.
            ssl_credentials (~grpc.ChannelCredentials): A
                ``ChannelCredentials`` instance for use with an SSL-enabled
                channel.
            scopes (Sequence[str]): A list of OAuth2 scopes to attach to requests.
            client_config (dict):
                A dictionary for call options for each method. See
                :func:`google.gax.construct_settings` for the structure of
                this data. Falls back to the default config if not specified
                or the specified config is missing data points.
            lib_name (str): The API library software used for calling
                the service. (Unless you are writing an API client itself,
                leave this as default.)
            lib_version (str): The API library software version used
                for calling the service. (Unless you are writing an API client
                itself, leave this as default.)
            metrics_headers (dict): A dictionary of values for tracking
                client library metrics. Ultimately serializes to a string
                (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be
                considered private.
        """
        # Unless the calling application specifically requested
        # OAuth scopes, request everything.
        if scopes is None:
            scopes = self._ALL_SCOPES

        # Initialize an empty client config, if none is set.
        if client_config is None:
            client_config = {}

        # Initialize metrics_headers as an ordered dictionary
        # (cuts down on cardinality of the resulting string slightly).
        metrics_headers = collections.OrderedDict(metrics_headers)
        metrics_headers['gl-python'] = platform.python_version()

        # The library may or may not be set, depending on what is
        # calling this client. Newer client libraries set the library name
        # and version.
        if lib_name:
            metrics_headers[lib_name] = lib_version

        # Finally, track the GAPIC package version.
        metrics_headers['gapic'] = pkg_resources.get_distribution(
            'google-cloud-spanner', ).version

        # Load the configuration defaults.
        defaults = api_callable.construct_settings(
            'google.spanner.v1.Spanner',
            spanner_client_config.config,
            client_config,
            config.STATUS_CODE_NAMES,
            metrics_headers=metrics_headers, )
        self.spanner_stub = config.create_stub(
            spanner_pb2.SpannerStub,
            channel=channel,
            service_path=self.SERVICE_ADDRESS,
            service_port=self.DEFAULT_SERVICE_PORT,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)

        self._create_session = api_callable.create_api_call(
            self.spanner_stub.CreateSession,
            settings=defaults['create_session'])
        self._get_session = api_callable.create_api_call(
            self.spanner_stub.GetSession, settings=defaults['get_session'])
        self._delete_session = api_callable.create_api_call(
            self.spanner_stub.DeleteSession,
            settings=defaults['delete_session'])
        self._execute_sql = api_callable.create_api_call(
            self.spanner_stub.ExecuteSql, settings=defaults['execute_sql'])
        self._execute_streaming_sql = api_callable.create_api_call(
            self.spanner_stub.ExecuteStreamingSql,
            settings=defaults['execute_streaming_sql'])
        self._read = api_callable.create_api_call(
            self.spanner_stub.Read, settings=defaults['read'])
        self._streaming_read = api_callable.create_api_call(
            self.spanner_stub.StreamingRead,
            settings=defaults['streaming_read'])
        self._begin_transaction = api_callable.create_api_call(
            self.spanner_stub.BeginTransaction,
            settings=defaults['begin_transaction'])
        self._commit = api_callable.create_api_call(
            self.spanner_stub.Commit, settings=defaults['commit'])
        self._rollback = api_callable.create_api_call(
            self.spanner_stub.Rollback, settings=defaults['rollback'])

    # Service calls
    def create_session(self, database, options=None):
        """
        Creates a new session. A session can be used to perform
        transactions that read and/or modify data in a Cloud Spanner database.
        Sessions are meant to be reused for many consecutive
        transactions.

        Sessions can only execute one transaction at a time. To execute
        multiple concurrent read-write/write-only transactions, create
        multiple sessions. Note that standalone reads and queries use a
        transaction internally, and count toward the one transaction
        limit.

        Cloud Spanner limits the number of sessions that can exist at any given
        time; thus, it is a good idea to delete idle and/or unneeded sessions.
        Aside from explicit deletes, Cloud Spanner can delete sessions for which no
        operations are sent for more than an hour. If a session is deleted,
        requests to it return ``NOT_FOUND``.

        Idle sessions can be kept alive by sending a trivial SQL query
        periodically, e.g., ``\"SELECT 1\"``.

        Example:
            >>> from google.cloud import spanner_v1
            >>>
            >>> client = spanner_v1.SpannerClient()
            >>>
            >>> database = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]')
            >>>
            >>> response = client.create_session(database)

        Args:
            database (str): Required. The database in which the new session is created.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_v1.types.Session` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_pb2.CreateSessionRequest(database=database)
        return self._create_session(request, options)

    def get_session(self, name, options=None):
        """
        Gets a session. Returns ``NOT_FOUND`` if the session does not exist.
        This is mainly useful for determining whether a session is still
        alive.

        Example:
            >>> from google.cloud import spanner_v1
            >>>
            >>> client = spanner_v1.SpannerClient()
            >>>
            >>> name = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
            >>>
            >>> response = client.get_session(name)

        Args:
            name (str): Required. The name of the session to retrieve.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_v1.types.Session` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_pb2.GetSessionRequest(name=name)
        return self._get_session(request, options)

    def delete_session(self, name, options=None):
        """
        Ends a session, releasing server resources associated with it.

        Example:
            >>> from google.cloud import spanner_v1
            >>>
            >>> client = spanner_v1.SpannerClient()
            >>>
            >>> name = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
            >>>
            >>> client.delete_session(name)

        Args:
            name (str): Required. The name of the session to delete.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_pb2.DeleteSessionRequest(name=name)
        self._delete_session(request, options)

    def execute_sql(self,
                    session,
                    sql,
                    transaction=None,
                    params=None,
                    param_types=None,
                    resume_token=None,
                    query_mode=None,
                    options=None):
        """
        Executes an SQL query, returning all rows in a single reply. This
        method cannot be used to return a result set larger than 10 MiB;
        if the query yields more data than that, the query fails with
        a ``FAILED_PRECONDITION`` error.

        Queries inside read-write transactions might return ``ABORTED``. If
        this occurs, the application should restart the transaction from
        the beginning. See ``Transaction`` for more details.

        Larger result sets can be fetched in streaming fashion by calling
        ``ExecuteStreamingSql`` instead.

        Example:
            >>> from google.cloud import spanner_v1
            >>>
            >>> client = spanner_v1.SpannerClient()
            >>>
            >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
            >>> sql = ''
            >>>
            >>> response = client.execute_sql(session, sql)

        Args:
            session (str): Required. The session in which the SQL query should be performed.
            sql (str): Required. The SQL query string.
            transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. If none is provided, the default is a
                temporary read-only transaction with strong concurrency.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_v1.types.TransactionSelector`
            params (Union[dict, ~google.cloud.spanner_v1.types.Struct]): The SQL query string can contain parameter placeholders. A parameter
                placeholder consists of ``'@'`` followed by the parameter
                name. Parameter names consist of any combination of letters,
                numbers, and underscores.

                Parameters can appear anywhere that a literal value is expected.  The same
                parameter name can be used more than once, for example:
                ``\"WHERE id > @msg_id AND id < @msg_id + 100\"``

                It is an error to execute an SQL query with unbound parameters.

                Parameter values are specified using ``params``, which is a JSON
                object whose keys are parameter names, and whose values are the
                corresponding parameter values.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_v1.types.Struct`
            param_types (dict[str -> Union[dict, ~google.cloud.spanner_v1.types.Type]]): It is not always possible for Cloud Spanner to infer the right SQL type
                from a JSON value.  For example, values of type ``BYTES`` and values
                of type ``STRING`` both appear in ``params`` as JSON strings.

                In these cases, ``param_types`` can be used to specify the exact
                SQL type for some or all of the SQL query parameters. See the
                definition of ``Type`` for more information
                about SQL types.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_v1.types.Type`
            resume_token (bytes): If this request is resuming a previously interrupted SQL query
                execution, ``resume_token`` should be copied from the last
                ``PartialResultSet`` yielded before the interruption. Doing this
                enables the new SQL query execution to resume where the last one left
                off. The rest of the request parameters must exactly match the
                request that yielded this token.
            query_mode (~google.cloud.spanner_v1.types.QueryMode): Used to control the amount of debugging information returned in
                ``ResultSetStats``.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_v1.types.ResultSet` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_pb2.ExecuteSqlRequest(
            session=session,
            sql=sql,
            transaction=transaction,
            params=params,
            param_types=param_types,
            resume_token=resume_token,
            query_mode=query_mode)
        return self._execute_sql(request, options)

    def execute_streaming_sql(self,
                              session,
                              sql,
                              transaction=None,
                              params=None,
                              param_types=None,
                              resume_token=None,
                              query_mode=None,
                              options=None):
        """
        Like ``ExecuteSql``, except returns the result
        set as a stream. Unlike ``ExecuteSql``, there
        is no limit on the size of the returned result set. However, no
        individual row in the result set can exceed 100 MiB, and no
        column value can exceed 10 MiB.

        Example:
            >>> from google.cloud import spanner_v1
            >>>
            >>> client = spanner_v1.SpannerClient()
            >>>
            >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
            >>> sql = ''
            >>>
            >>> for element in client.execute_streaming_sql(session, sql):
            ...     # process element
            ...     pass

        Args:
            session (str): Required. The session in which the SQL query should be performed.
            sql (str): Required. The SQL query string.
            transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. If none is provided, the default is a
                temporary read-only transaction with strong concurrency.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_v1.types.TransactionSelector`
            params (Union[dict, ~google.cloud.spanner_v1.types.Struct]): The SQL query string can contain parameter placeholders. A parameter
                placeholder consists of ``'@'`` followed by the parameter
                name. Parameter names consist of any combination of letters,
                numbers, and underscores.

                Parameters can appear anywhere that a literal value is expected.  The same
                parameter name can be used more than once, for example:
                ``\"WHERE id > @msg_id AND id < @msg_id + 100\"``

                It is an error to execute an SQL query with unbound parameters.

                Parameter values are specified using ``params``, which is a JSON
                object whose keys are parameter names, and whose values are the
                corresponding parameter values.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_v1.types.Struct`
            param_types (dict[str -> Union[dict, ~google.cloud.spanner_v1.types.Type]]): It is not always possible for Cloud Spanner to infer the right SQL type
                from a JSON value.  For example, values of type ``BYTES`` and values
                of type ``STRING`` both appear in ``params`` as JSON strings.

                In these cases, ``param_types`` can be used to specify the exact
                SQL type for some or all of the SQL query parameters. See the
                definition of ``Type`` for more information
                about SQL types.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_v1.types.Type`
            resume_token (bytes): If this request is resuming a previously interrupted SQL query
                execution, ``resume_token`` should be copied from the last
                ``PartialResultSet`` yielded before the interruption. Doing this
                enables the new SQL query execution to resume where the last one left
                off. The rest of the request parameters must exactly match the
                request that yielded this token.
            query_mode (~google.cloud.spanner_v1.types.QueryMode): Used to control the amount of debugging information returned in
                ``ResultSetStats``.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            Iterable[~google.cloud.spanner_v1.types.PartialResultSet].

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_pb2.ExecuteSqlRequest(
            session=session,
            sql=sql,
            transaction=transaction,
            params=params,
            param_types=param_types,
            resume_token=resume_token,
            query_mode=query_mode)
        return self._execute_streaming_sql(request, options)

    def read(self,
             session,
             table,
             columns,
             key_set,
             transaction=None,
             index=None,
             limit=None,
             resume_token=None,
             options=None):
        """
        Reads rows from the database using key lookups and scans, as a
        simple key/value style alternative to
        ``ExecuteSql``.  This method cannot be used to
        return a result set larger than 10 MiB; if the read matches more
        data than that, the read fails with a ``FAILED_PRECONDITION``
        error.

        Reads inside read-write transactions might return ``ABORTED``. If
        this occurs, the application should restart the transaction from
        the beginning. See ``Transaction`` for more details.

        Larger result sets can be yielded in streaming fashion by calling
        ``StreamingRead`` instead.

        Example:
            >>> from google.cloud import spanner_v1
            >>>
            >>> client = spanner_v1.SpannerClient()
            >>>
            >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
            >>> table = ''
            >>> columns = []
            >>> key_set = {}
            >>>
            >>> response = client.read(session, table, columns, key_set)

        Args:
            session (str): Required. The session in which the read should be performed.
            table (str): Required. The name of the table in the database to be read.
            columns (list[str]): The columns of ``table`` to be returned for each row matching
                this request.
            key_set (Union[dict, ~google.cloud.spanner_v1.types.KeySet]): Required. ``key_set`` identifies the rows to be yielded. ``key_set`` names the
                primary keys of the rows in ``table`` to be yielded, unless ``index``
                is present. If ``index`` is present, then ``key_set`` instead names
                index keys in ``index``.

                Rows are yielded in table primary key order (if ``index`` is empty)
                or index key order (if ``index`` is non-empty).

                It is not an error for the ``key_set`` to name rows that do not
                exist in the database. Read yields nothing for nonexistent rows.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_v1.types.KeySet`
            transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. If none is provided, the default is a
                temporary read-only transaction with strong concurrency.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_v1.types.TransactionSelector`
            index (str): If non-empty, the name of an index on ``table``. This index is
                used instead of the table primary key when interpreting ``key_set``
                and sorting result rows. See ``key_set`` for further information.
            limit (long): If greater than zero, only the first ``limit`` rows are yielded. If ``limit``
                is zero, the default is no limit.
            resume_token (bytes): If this request is resuming a previously interrupted read,
                ``resume_token`` should be copied from the last
                ``PartialResultSet`` yielded before the interruption. Doing this
                enables the new read to resume where the last read left off. The
                rest of the request parameters must exactly match the request
                that yielded this token.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_v1.types.ResultSet` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_pb2.ReadRequest(
            session=session,
            table=table,
            columns=columns,
            key_set=key_set,
            transaction=transaction,
            index=index,
            limit=limit,
            resume_token=resume_token)
        return self._read(request, options)

    def streaming_read(self,
                       session,
                       table,
                       columns,
                       key_set,
                       transaction=None,
                       index=None,
                       limit=None,
                       resume_token=None,
                       options=None):
        """
        Like ``Read``, except returns the result set as a
        stream. Unlike ``Read``, there is no limit on the
        size of the returned result set. However, no individual row in
        the result set can exceed 100 MiB, and no column value can exceed
        10 MiB.

        Example:
            >>> from google.cloud import spanner_v1
            >>>
            >>> client = spanner_v1.SpannerClient()
            >>>
            >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
            >>> table = ''
            >>> columns = []
            >>> key_set = {}
            >>>
            >>> for element in client.streaming_read(session, table, columns, key_set):
            ...     # process element
            ...     pass

        Args:
            session (str): Required. The session in which the read should be performed.
            table (str): Required. The name of the table in the database to be read.
            columns (list[str]): The columns of ``table`` to be returned for each row matching
                this request.
            key_set (Union[dict, ~google.cloud.spanner_v1.types.KeySet]): Required. ``key_set`` identifies the rows to be yielded. ``key_set`` names the
                primary keys of the rows in ``table`` to be yielded, unless ``index``
                is present. If ``index`` is present, then ``key_set`` instead names
                index keys in ``index``.

                Rows are yielded in table primary key order (if ``index`` is empty)
                or index key order (if ``index`` is non-empty).

                It is not an error for the ``key_set`` to name rows that do not
                exist in the database. Read yields nothing for nonexistent rows.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_v1.types.KeySet`
            transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. If none is provided, the default is a
                temporary read-only transaction with strong concurrency.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_v1.types.TransactionSelector`
            index (str): If non-empty, the name of an index on ``table``. This index is
                used instead of the table primary key when interpreting ``key_set``
                and sorting result rows. See ``key_set`` for further information.
            limit (long): If greater than zero, only the first ``limit`` rows are yielded. If ``limit``
                is zero, the default is no limit.
            resume_token (bytes): If this request is resuming a previously interrupted read,
                ``resume_token`` should be copied from the last
                ``PartialResultSet`` yielded before the interruption. Doing this
                enables the new read to resume where the last read left off. The
                rest of the request parameters must exactly match the request
                that yielded this token.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            Iterable[~google.cloud.spanner_v1.types.PartialResultSet].

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_pb2.ReadRequest(
            session=session,
            table=table,
            columns=columns,
            key_set=key_set,
            transaction=transaction,
            index=index,
            limit=limit,
            resume_token=resume_token)
        return self._streaming_read(request, options)

    def begin_transaction(self, session, options_, options=None):
        """
        Begins a new transaction. This step can often be skipped:
        ``Read``, ``ExecuteSql`` and
        ``Commit`` can begin a new transaction as a
        side-effect.

        Example:
            >>> from google.cloud import spanner_v1
            >>>
            >>> client = spanner_v1.SpannerClient()
            >>>
            >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
            >>> options_ = {}
            >>>
            >>> response = client.begin_transaction(session, options_)

        Args:
            session (str): Required. The session in which the transaction runs.
            options_ (Union[dict, ~google.cloud.spanner_v1.types.TransactionOptions]): Required. Options for the new transaction.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_v1.types.TransactionOptions`
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_v1.types.Transaction` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_pb2.BeginTransactionRequest(
            session=session, options=options_)
        return self._begin_transaction(request, options)

    def commit(self,
               session,
               mutations,
               transaction_id=None,
               single_use_transaction=None,
               options=None):
        """
        Commits a transaction. The request includes the mutations to be
        applied to rows in the database.

        ``Commit`` might return an ``ABORTED`` error. This can occur at any time;
        commonly, the cause is conflicts with concurrent
        transactions. However, it can also happen for a variety of other
        reasons. If ``Commit`` returns ``ABORTED``, the caller should re-attempt
        the transaction from the beginning, re-using the same session.

        Example:
            >>> from google.cloud import spanner_v1
            >>>
            >>> client = spanner_v1.SpannerClient()
            >>>
            >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
            >>> mutations = []
            >>>
            >>> response = client.commit(session, mutations)

        Args:
            session (str): Required. The session in which the transaction to be committed is running.
            mutations (list[Union[dict, ~google.cloud.spanner_v1.types.Mutation]]): The mutations to be executed when this transaction commits. All
                mutations are applied atomically, in the order they appear in
                this list.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_v1.types.Mutation`
            transaction_id (bytes): Commit a previously-started transaction.
            single_use_transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionOptions]): Execute mutations in a temporary transaction. Note that unlike
                commit of a previously-started transaction, commit with a
                temporary transaction is non-idempotent. That is, if the
                ``CommitRequest`` is sent to Cloud Spanner more than once (for
                instance, due to retries in the application, or in the
                transport library), it is possible that the mutations are
                executed more than once. If this is undesirable, use
                ``BeginTransaction`` and
                ``Commit`` instead.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.spanner_v1.types.TransactionOptions`
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Returns:
            A :class:`~google.cloud.spanner_v1.types.CommitResponse` instance.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        # Sanity check: We have some fields which are mutually exclusive;
        # raise ValueError if more than one is sent.
        oneof.check_oneof(
            transaction_id=transaction_id,
            single_use_transaction=single_use_transaction, )

        request = spanner_pb2.CommitRequest(
            session=session,
            mutations=mutations,
            transaction_id=transaction_id,
            single_use_transaction=single_use_transaction)
        return self._commit(request, options)

    def rollback(self, session, transaction_id, options=None):
        """
        Rolls back a transaction, releasing any locks it holds. It is a good
        idea to call this for any transaction that includes one or more
        ``Read`` or ``ExecuteSql`` requests and
        ultimately decides not to commit.

        ``Rollback`` returns ``OK`` if it successfully aborts the transaction, the
        transaction was already aborted, or the transaction is not
        found. ``Rollback`` never returns ``ABORTED``.

        Example:
            >>> from google.cloud import spanner_v1
            >>>
            >>> client = spanner_v1.SpannerClient()
            >>>
            >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
            >>> transaction_id = b''
            >>>
            >>> client.rollback(session, transaction_id)

        Args:
            session (str): Required. The session in which the transaction to roll back is running.
            transaction_id (bytes): Required. The transaction to roll back.
            options (~google.gax.CallOptions): Overrides the default
                settings for this call, e.g, timeout, retries etc.

        Raises:
            :exc:`google.gax.errors.GaxError` if the RPC is aborted.
            :exc:`ValueError` if the parameters are invalid.
        """
        request = spanner_pb2.RollbackRequest(
            session=session, transaction_id=transaction_id)
        self._rollback(request, options)
Exemple #21
0
class MetricServiceApi(object):
    """
    Manages metric descriptors, monitored resource descriptors, and
    time series data.
    """

    SERVICE_ADDRESS = 'monitoring.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _CODE_GEN_NAME_VERSION = 'gapic/0.1.0'

    _GAX_VERSION = pkg_resources.get_distribution('google-gax').version

    _PAGE_DESCRIPTORS = {
        'list_monitored_resource_descriptors':
        _PageDesc('page_token', 'next_page_token', 'resource_descriptors'),
        'list_metric_descriptors':
        _PageDesc('page_token', 'next_page_token', 'metric_descriptors'),
        'list_time_series':
        _PageDesc('page_token', 'next_page_token', 'time_series')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = ()

    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')
    _METRIC_DESCRIPTOR_PATH_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/metricDescriptors/{metric_descriptor_path=**}')
    _MONITORED_RESOURCE_DESCRIPTOR_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}'
    )

    @classmethod
    def project_path(cls, project):
        """Returns a fully-qualified project resource name string."""
        return cls._PROJECT_PATH_TEMPLATE.render({
            'project': project,
        })

    @classmethod
    def metric_descriptor_path_path(cls, project, metric_descriptor_path):
        """Returns a fully-qualified metric_descriptor_path resource name string."""
        return cls._METRIC_DESCRIPTOR_PATH_PATH_TEMPLATE.render({
            'project':
            project,
            'metric_descriptor_path':
            metric_descriptor_path,
        })

    @classmethod
    def monitored_resource_descriptor_path(cls, project,
                                           monitored_resource_descriptor):
        """Returns a fully-qualified monitored_resource_descriptor resource name string."""
        return cls._MONITORED_RESOURCE_DESCRIPTOR_PATH_TEMPLATE.render({
            'project':
            project,
            'monitored_resource_descriptor':
            monitored_resource_descriptor,
        })

    @classmethod
    def match_project_from_project_name(cls, project_name):
        """Parses the project from a project resource.

        Args:
          project_name (string): A fully-qualified path representing a project
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')

    @classmethod
    def match_project_from_metric_descriptor_path_name(
            cls, metric_descriptor_path_name):
        """Parses the project from a metric_descriptor_path resource.

        Args:
          metric_descriptor_path_name (string): A fully-qualified path representing a metric_descriptor_path
            resource.

        Returns:
          A string representing the project.
        """
        return cls._METRIC_DESCRIPTOR_PATH_PATH_TEMPLATE.match(
            metric_descriptor_path_name).get('project')

    @classmethod
    def match_metric_descriptor_path_from_metric_descriptor_path_name(
            cls, metric_descriptor_path_name):
        """Parses the metric_descriptor_path from a metric_descriptor_path resource.

        Args:
          metric_descriptor_path_name (string): A fully-qualified path representing a metric_descriptor_path
            resource.

        Returns:
          A string representing the metric_descriptor_path.
        """
        return cls._METRIC_DESCRIPTOR_PATH_PATH_TEMPLATE.match(
            metric_descriptor_path_name).get('metric_descriptor_path')

    @classmethod
    def match_project_from_monitored_resource_descriptor_name(
            cls, monitored_resource_descriptor_name):
        """Parses the project from a monitored_resource_descriptor resource.

        Args:
          monitored_resource_descriptor_name (string): A fully-qualified path representing a monitored_resource_descriptor
            resource.

        Returns:
          A string representing the project.
        """
        return cls._MONITORED_RESOURCE_DESCRIPTOR_PATH_TEMPLATE.match(
            monitored_resource_descriptor_name).get('project')

    @classmethod
    def match_monitored_resource_descriptor_from_monitored_resource_descriptor_name(
            cls, monitored_resource_descriptor_name):
        """Parses the monitored_resource_descriptor from a monitored_resource_descriptor resource.

        Args:
          monitored_resource_descriptor_name (string): A fully-qualified path representing a monitored_resource_descriptor
            resource.

        Returns:
          A string representing the monitored_resource_descriptor.
        """
        return cls._MONITORED_RESOURCE_DESCRIPTOR_PATH_TEMPLATE.match(
            monitored_resource_descriptor_name).get(
                'monitored_resource_descriptor')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 metadata_transformer=None,
                 ssl_creds=None,
                 scopes=None,
                 client_config=None,
                 app_name='gax',
                 app_version=_GAX_VERSION):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          ssl_creds (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          metadata_transformer (Callable[[], list]): A function that creates
             the metadata for requests.
          app_name (string): The codename of the calling service.
          app_version (string): The version of the calling service.

        Returns:
          A MetricServiceApi object.
        """
        if scopes is None:
            scopes = self._ALL_SCOPES
        if client_config is None:
            client_config = {}
        goog_api_client = '{}/{} {} gax/{} python/{}'.format(
            app_name, app_version, self._CODE_GEN_NAME_VERSION,
            self._GAX_VERSION, platform.python_version())
        metadata = [('x-goog-api-client', goog_api_client)]
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'metric_service_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.monitoring.v3.MetricService',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            kwargs={'metadata': metadata},
            page_descriptors=self._PAGE_DESCRIPTORS)
        self.metric_service_stub = config.create_stub(
            metric_service_pb2.MetricServiceStub,
            service_path,
            port,
            ssl_creds=ssl_creds,
            channel=channel,
            metadata_transformer=metadata_transformer,
            scopes=scopes)

        self._list_monitored_resource_descriptors = api_callable.create_api_call(
            self.metric_service_stub.ListMonitoredResourceDescriptors,
            settings=defaults['list_monitored_resource_descriptors'])
        self._get_monitored_resource_descriptor = api_callable.create_api_call(
            self.metric_service_stub.GetMonitoredResourceDescriptor,
            settings=defaults['get_monitored_resource_descriptor'])
        self._list_metric_descriptors = api_callable.create_api_call(
            self.metric_service_stub.ListMetricDescriptors,
            settings=defaults['list_metric_descriptors'])
        self._get_metric_descriptor = api_callable.create_api_call(
            self.metric_service_stub.GetMetricDescriptor,
            settings=defaults['get_metric_descriptor'])
        self._create_metric_descriptor = api_callable.create_api_call(
            self.metric_service_stub.CreateMetricDescriptor,
            settings=defaults['create_metric_descriptor'])
        self._delete_metric_descriptor = api_callable.create_api_call(
            self.metric_service_stub.DeleteMetricDescriptor,
            settings=defaults['delete_metric_descriptor'])
        self._list_time_series = api_callable.create_api_call(
            self.metric_service_stub.ListTimeSeries,
            settings=defaults['list_time_series'])
        self._create_time_series = api_callable.create_api_call(
            self.metric_service_stub.CreateTimeSeries,
            settings=defaults['create_time_series'])

    # Service calls
    def list_monitored_resource_descriptors(self,
                                            name,
                                            filter_='',
                                            page_size=0,
                                            options=None):
        """
        Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import metric_service_api
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = metric_service_api.MetricServiceApi()
          >>> name = api.project_path('[PROJECT]')
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_monitored_resource_descriptors(name):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_monitored_resource_descriptors(name, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          name (string): The project on which to execute the request. The format is
            ``\"projects/{project_id_or_number}\"``.
          filter_ (string): An optional `filter <https://cloud.google.com/monitoring/api/v3/filters>`_ describing
            the descriptors to be returned.  The filter can reference
            the descriptor's type and labels. For example, the
            following filter returns only Google Compute Engine descriptors
            that have an ``id`` label:

                resource.type = starts_with(\"gce_\") AND resource.label:id
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.api.monitored_resource_pb2.MonitoredResourceDescriptor` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = metric_service_pb2.ListMonitoredResourceDescriptorsRequest(
            name=name, filter=filter_, page_size=page_size)
        return self._list_monitored_resource_descriptors(request, options)

    def get_monitored_resource_descriptor(self, name, options=None):
        """
        Gets a single monitored resource descriptor. This method does not require a Stackdriver account.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import metric_service_api
          >>> api = metric_service_api.MetricServiceApi()
          >>> name = api.monitored_resource_descriptor_path('[PROJECT]', '[MONITORED_RESOURCE_DESCRIPTOR]')
          >>> response = api.get_monitored_resource_descriptor(name)

        Args:
          name (string): The monitored resource descriptor to get.  The format is
            ``\"projects/{project_id_or_number}/monitoredResourceDescriptors/{resource_type}\"``.
            The ``{resource_type}`` is a predefined type, such as
            ``cloudsql_database``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.api.monitored_resource_pb2.MonitoredResourceDescriptor` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = metric_service_pb2.GetMonitoredResourceDescriptorRequest(
            name=name)
        return self._get_monitored_resource_descriptor(request, options)

    def list_metric_descriptors(self,
                                name,
                                filter_='',
                                page_size=0,
                                options=None):
        """
        Lists metric descriptors that match a filter. This method does not require a Stackdriver account.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import metric_service_api
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = metric_service_api.MetricServiceApi()
          >>> name = api.project_path('[PROJECT]')
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_metric_descriptors(name):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_metric_descriptors(name, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          name (string): The project on which to execute the request. The format is
            ``\"projects/{project_id_or_number}\"``.
          filter_ (string): If this field is empty, all custom and
            system-defined metric descriptors are returned.
            Otherwise, the `filter <https://cloud.google.com/monitoring/api/v3/filters>`_
            specifies which metric descriptors are to be
            returned. For example, the following filter matches all
            `custom metrics <https://cloud.google.com/monitoring/custom-metrics>`_:

                metric.type = starts_with(\"custom.googleapis.com/\")
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.api.metric_pb2.MetricDescriptor` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = metric_service_pb2.ListMetricDescriptorsRequest(
            name=name, filter=filter_, page_size=page_size)
        return self._list_metric_descriptors(request, options)

    def get_metric_descriptor(self, name, options=None):
        """
        Gets a single metric descriptor. This method does not require a Stackdriver account.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import metric_service_api
          >>> api = metric_service_api.MetricServiceApi()
          >>> name = api.metric_descriptor_path_path('[PROJECT]', '[METRIC_DESCRIPTOR_PATH]')
          >>> response = api.get_metric_descriptor(name)

        Args:
          name (string): The metric descriptor on which to execute the request. The format is
            ``\"projects/{project_id_or_number}/metricDescriptors/{metric_id}\"``.
            An example value of ``{metric_id}`` is
            ``\"compute.googleapis.com/instance/disk/read_bytes_count\"``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.api.metric_pb2.MetricDescriptor` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = metric_service_pb2.GetMetricDescriptorRequest(name=name)
        return self._get_metric_descriptor(request, options)

    def create_metric_descriptor(self, name, metric_descriptor, options=None):
        """
        Creates a new metric descriptor.
        User-created metric descriptors define
        `custom metrics <https://cloud.google.com/monitoring/custom-metrics>`_.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import metric_service_api
          >>> from google.api import metric_pb2 as api_metric_pb2
          >>> api = metric_service_api.MetricServiceApi()
          >>> name = api.project_path('[PROJECT]')
          >>> metric_descriptor = api_metric_pb2.MetricDescriptor()
          >>> response = api.create_metric_descriptor(name, metric_descriptor)

        Args:
          name (string): The project on which to execute the request. The format is
            ``\"projects/{project_id_or_number}\"``.
          metric_descriptor (:class:`google.api.metric_pb2.MetricDescriptor`): The new `custom metric <https://cloud.google.com/monitoring/custom-metrics>`_
            descriptor.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.api.metric_pb2.MetricDescriptor` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = metric_service_pb2.CreateMetricDescriptorRequest(
            name=name, metric_descriptor=metric_descriptor)
        return self._create_metric_descriptor(request, options)

    def delete_metric_descriptor(self, name, options=None):
        """
        Deletes a metric descriptor. Only user-created
        `custom metrics <https://cloud.google.com/monitoring/custom-metrics>`_ can be deleted.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import metric_service_api
          >>> api = metric_service_api.MetricServiceApi()
          >>> name = api.metric_descriptor_path_path('[PROJECT]', '[METRIC_DESCRIPTOR_PATH]')
          >>> api.delete_metric_descriptor(name)

        Args:
          name (string): The metric descriptor on which to execute the request. The format is
            ``\"projects/{project_id_or_number}/metricDescriptors/{metric_id}\"``.
            An example of ``{metric_id}`` is:
            ``\"custom.googleapis.com/my_test_metric\"``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = metric_service_pb2.DeleteMetricDescriptorRequest(name=name)
        self._delete_metric_descriptor(request, options)

    def list_time_series(self,
                         name,
                         filter_,
                         interval,
                         view,
                         aggregation=None,
                         order_by='',
                         page_size=0,
                         options=None):
        """
        Lists time series that match a filter. This method does not require a Stackdriver account.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import metric_service_api
          >>> from google.cloud.gapic.monitoring.v3 import enums
          >>> from google.monitoring.v3 import common_pb2
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = metric_service_api.MetricServiceApi()
          >>> name = api.project_path('[PROJECT]')
          >>> filter_ = ''
          >>> interval = common_pb2.TimeInterval()
          >>> view = enums.ListTimeSeriesRequest.TimeSeriesView.FULL
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_time_series(name, filter_, interval, view):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_time_series(name, filter_, interval, view, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          name (string): The project on which to execute the request. The format is
            \"projects/{project_id_or_number}\".
          filter_ (string): A `monitoring filter <https://cloud.google.com/monitoring/api/v3/filters>`_ that specifies which time
            series should be returned.  The filter must specify a single metric type,
            and can additionally specify metric labels and other information. For
            example:

                metric.type = \"compute.googleapis.com/instance/cpu/usage_time\" AND
                    metric.label.instance_name = \"my-instance-name\"
          interval (:class:`google.monitoring.v3.common_pb2.TimeInterval`): The time interval for which results should be returned. Only time series
            that contain data points in the specified interval are included
            in the response.
          aggregation (:class:`google.monitoring.v3.common_pb2.Aggregation`): By default, the raw time series data is returned.
            Use this field to combine multiple time series for different
            views of the data.
          order_by (string): Specifies the order in which the points of the time series should
            be returned.  By default, results are not ordered.  Currently,
            this field must be left blank.
          view (enum :class:`google.cloud.gapic.monitoring.v3.enums.ListTimeSeriesRequest.TimeSeriesView`): Specifies which information is returned about the time series.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.monitoring.v3.metric_pb2.TimeSeries` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        if aggregation is None:
            aggregation = common_pb2.Aggregation()
        request = metric_service_pb2.ListTimeSeriesRequest(
            name=name,
            filter=filter_,
            interval=interval,
            view=view,
            aggregation=aggregation,
            order_by=order_by,
            page_size=page_size)
        return self._list_time_series(request, options)

    def create_time_series(self, name, time_series, options=None):
        """
        Creates or adds data to one or more time series.
        The response is empty if all time series in the request were written.
        If any time series could not be written, a corresponding failure message is
        included in the error response.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import metric_service_api
          >>> from google.monitoring.v3 import metric_pb2 as v3_metric_pb2
          >>> api = metric_service_api.MetricServiceApi()
          >>> name = api.project_path('[PROJECT]')
          >>> time_series = []
          >>> api.create_time_series(name, time_series)

        Args:
          name (string): The project on which to execute the request. The format is
            ``\"projects/{project_id_or_number}\"``.
          time_series (list[:class:`google.monitoring.v3.metric_pb2.TimeSeries`]): The new data to be added to a list of time series.
            Adds at most one data point to each of several time series.  The new data
            point must be more recent than any other point in its time series.  Each
            ``TimeSeries`` value must fully specify a unique time series by supplying
            all label values for the metric and the monitored resource.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = metric_service_pb2.CreateTimeSeriesRequest(
            name=name, time_series=time_series)
        self._create_time_series(request, options)
Exemple #22
0
class ReportErrorsServiceClient(object):
    """An API for reporting error events."""

    SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = ('https://www.googleapis.com/auth/cloud-platform', )

    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')

    @classmethod
    def project_path(cls, project):
        """Returns a fully-qualified project resource name string."""
        return cls._PROJECT_PATH_TEMPLATE.render({
            'project': project,
        })

    @classmethod
    def match_project_from_project_name(cls, project_name):
        """Parses the project from a project resource.

        Args:
          project_name (string): A fully-qualified path representing a project
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 credentials=None,
                 ssl_credentials=None,
                 scopes=None,
                 client_config=None,
                 app_name=None,
                 app_version='',
                 lib_name=None,
                 lib_version='',
                 metrics_headers=()):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          credentials (object): The authorization credentials to attach to
            requests. These credentials identify this application to the
            service.
          ssl_credentials (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          scopes (list[string]): A list of OAuth2 scopes to attach to requests.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          app_name (string): The name of the application calling
            the service. Recommended for analytics purposes.
          app_version (string): The version of the application calling
            the service. Recommended for analytics purposes.
          lib_name (string): The API library software used for calling
            the service. (Unless you are writing an API client itself,
            leave this as default.)
          lib_version (string): The API library software version used
            for calling the service. (Unless you are writing an API client
            itself, leave this as default.)
          metrics_headers (dict): A dictionary of values for tracking
            client library metrics. Ultimately serializes to a string
            (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be
            considered private.

        Returns:
          A ReportErrorsServiceClient object.
        """
        # Unless the calling application specifically requested
        # OAuth scopes, request everything.
        if scopes is None:
            scopes = self._ALL_SCOPES

        # Initialize an empty client config, if none is set.
        if client_config is None:
            client_config = {}

        # Initialize metrics_headers as an ordered dictionary
        # (cuts down on cardinality of the resulting string slightly).
        metrics_headers = collections.OrderedDict(metrics_headers)
        metrics_headers['gl-python'] = platform.python_version()

        # The library may or may not be set, depending on what is
        # calling this client. Newer client libraries set the library name
        # and version.
        if lib_name:
            metrics_headers[lib_name] = lib_version

        # Finally, track the GAPIC package version.
        metrics_headers['gapic'] = pkg_resources.get_distribution(
            'gapic-google-cloud-error-reporting-v1beta1', ).version

        # Load the configuration defaults.
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'report_errors_service_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.devtools.clouderrorreporting.v1beta1.ReportErrorsService',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            metrics_headers=metrics_headers,
        )
        self.report_errors_service_stub = config.create_stub(
            report_errors_service_pb2.ReportErrorsServiceStub,
            channel=channel,
            service_path=service_path,
            service_port=port,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)

        self._report_error_event = api_callable.create_api_call(
            self.report_errors_service_stub.ReportErrorEvent,
            settings=defaults['report_error_event'])

    # Service calls
    def report_error_event(self, project_name, event, options=None):
        """
        Report an individual error event.
        This endpoint accepts <strong>either</strong> an OAuth token,
        <strong>or</strong> an
        <a href=\"https://support.google.com/cloud/answer/6158862\">API key</a>
        for authentication. To use an API key, append it to the URL as the value of
        a ``key`` parameter. For example:
        <pre>POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456</pre>

        Example:
          >>> from google.cloud.gapic.errorreporting.v1beta1 import report_errors_service_client
          >>> from google.cloud.proto.devtools.clouderrorreporting.v1beta1 import report_errors_service_pb2
          >>> api = report_errors_service_client.ReportErrorsServiceClient()
          >>> project_name = api.project_path('[PROJECT]')
          >>> event = report_errors_service_pb2.ReportedErrorEvent()
          >>> response = api.report_error_event(project_name, event)

        Args:
          project_name (string): [Required] The resource name of the Google Cloud Platform project. Written
            as ``projects/`` plus the
            `Google Cloud Platform project ID <https://support.google.com/cloud/answer/6158840>`_.
            Example: ``projects/my-project-123``.
          event (:class:`google.cloud.proto.devtools.clouderrorreporting.v1beta1.report_errors_service_pb2.ReportedErrorEvent`): [Required] The error event to be reported.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.devtools.clouderrorreporting.v1beta1.report_errors_service_pb2.ReportErrorEventResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = report_errors_service_pb2.ReportErrorEventRequest(
            project_name=project_name, event=event)
        return self._report_error_event(request, options)
Exemple #23
0
class ConfigServiceV2Api(object):
    """
    Service for configuring sinks used to export log entries outside Stackdriver
    Logging.
    """

    SERVICE_ADDRESS = 'logging.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _CODE_GEN_NAME_VERSION = 'gapic/0.1.0'

    _GAX_VERSION = pkg_resources.get_distribution('google-gax').version

    _PAGE_DESCRIPTORS = {
        'list_sinks': _PageDesc('page_token', 'next_page_token', 'sinks')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = (
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/cloud-platform.read-only',
        'https://www.googleapis.com/auth/logging.admin',
        'https://www.googleapis.com/auth/logging.read',
        'https://www.googleapis.com/auth/logging.write',
    )

    _PARENT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')
    _SINK_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/sinks/{sink}')

    @classmethod
    def parent_path(cls, project):
        """Returns a fully-qualified parent resource name string."""
        return cls._PARENT_PATH_TEMPLATE.render({
            'project': project,
        })

    @classmethod
    def sink_path(cls, project, sink):
        """Returns a fully-qualified sink resource name string."""
        return cls._SINK_PATH_TEMPLATE.render({
            'project': project,
            'sink': sink,
        })

    @classmethod
    def match_project_from_parent_name(cls, parent_name):
        """Parses the project from a parent resource.

        Args:
          parent_name (string): A fully-qualified path representing a parent
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PARENT_PATH_TEMPLATE.match(parent_name).get('project')

    @classmethod
    def match_project_from_sink_name(cls, sink_name):
        """Parses the project from a sink resource.

        Args:
          sink_name (string): A fully-qualified path representing a sink
            resource.

        Returns:
          A string representing the project.
        """
        return cls._SINK_PATH_TEMPLATE.match(sink_name).get('project')

    @classmethod
    def match_sink_from_sink_name(cls, sink_name):
        """Parses the sink from a sink resource.

        Args:
          sink_name (string): A fully-qualified path representing a sink
            resource.

        Returns:
          A string representing the sink.
        """
        return cls._SINK_PATH_TEMPLATE.match(sink_name).get('sink')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 metadata_transformer=None,
                 ssl_creds=None,
                 scopes=None,
                 client_config=None,
                 app_name='gax',
                 app_version=_GAX_VERSION):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          ssl_creds (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          metadata_transformer (Callable[[], list]): A function that creates
             the metadata for requests.
          app_name (string): The codename of the calling service.
          app_version (string): The version of the calling service.

        Returns:
          A ConfigServiceV2Api object.
        """
        if scopes is None:
            scopes = self._ALL_SCOPES
        if client_config is None:
            client_config = {}
        goog_api_client = '{}/{} {} gax/{} python/{}'.format(
            app_name, app_version, self._CODE_GEN_NAME_VERSION,
            self._GAX_VERSION, platform.python_version())
        metadata = [('x-goog-api-client', goog_api_client)]
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'config_service_v2_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.logging.v2.ConfigServiceV2',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            kwargs={'metadata': metadata},
            page_descriptors=self._PAGE_DESCRIPTORS)
        self.config_service_v2_stub = config.create_stub(
            logging_config_pb2.ConfigServiceV2Stub,
            service_path,
            port,
            ssl_creds=ssl_creds,
            channel=channel,
            metadata_transformer=metadata_transformer,
            scopes=scopes)

        self._list_sinks = api_callable.create_api_call(
            self.config_service_v2_stub.ListSinks,
            settings=defaults['list_sinks'])
        self._get_sink = api_callable.create_api_call(
            self.config_service_v2_stub.GetSink, settings=defaults['get_sink'])
        self._create_sink = api_callable.create_api_call(
            self.config_service_v2_stub.CreateSink,
            settings=defaults['create_sink'])
        self._update_sink = api_callable.create_api_call(
            self.config_service_v2_stub.UpdateSink,
            settings=defaults['update_sink'])
        self._delete_sink = api_callable.create_api_call(
            self.config_service_v2_stub.DeleteSink,
            settings=defaults['delete_sink'])

    # Service calls
    def list_sinks(self, parent, page_size=0, options=None):
        """
        Lists sinks.

        Example:
          >>> from google.cloud.gapic.logging.v2 import config_service_v2_api
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = config_service_v2_api.ConfigServiceV2Api()
          >>> parent = api.parent_path('[PROJECT]')
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_sinks(parent):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_sinks(parent, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          parent (string): Required. The cloud resource containing the sinks.
            Example: ``\"projects/my-logging-project\"``.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.logging.v2.logging_config_pb2.LogSink` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = logging_config_pb2.ListSinksRequest(parent=parent,
                                                      page_size=page_size)
        return self._list_sinks(request, options)

    def get_sink(self, sink_name, options=None):
        """
        Gets a sink.

        Example:
          >>> from google.cloud.gapic.logging.v2 import config_service_v2_api
          >>> api = config_service_v2_api.ConfigServiceV2Api()
          >>> sink_name = api.sink_path('[PROJECT]', '[SINK]')
          >>> response = api.get_sink(sink_name)

        Args:
          sink_name (string): Required. The resource name of the sink to return.
            Example: ``\"projects/my-project-id/sinks/my-sink-id\"``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.logging.v2.logging_config_pb2.LogSink` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = logging_config_pb2.GetSinkRequest(sink_name=sink_name)
        return self._get_sink(request, options)

    def create_sink(self, parent, sink, options=None):
        """
        Creates a sink.

        Example:
          >>> from google.cloud.gapic.logging.v2 import config_service_v2_api
          >>> from google.logging.v2 import logging_config_pb2
          >>> api = config_service_v2_api.ConfigServiceV2Api()
          >>> parent = api.parent_path('[PROJECT]')
          >>> sink = logging_config_pb2.LogSink()
          >>> response = api.create_sink(parent, sink)

        Args:
          parent (string): Required. The resource in which to create the sink.
            Example: ``\"projects/my-project-id\"``.
            The new sink must be provided in the request.
          sink (:class:`google.logging.v2.logging_config_pb2.LogSink`): Required. The new sink, whose ``name`` parameter is a sink identifier that
            is not already in use.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.logging.v2.logging_config_pb2.LogSink` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = logging_config_pb2.CreateSinkRequest(parent=parent,
                                                       sink=sink)
        return self._create_sink(request, options)

    def update_sink(self, sink_name, sink, options=None):
        """
        Updates or creates a sink.

        Example:
          >>> from google.cloud.gapic.logging.v2 import config_service_v2_api
          >>> from google.logging.v2 import logging_config_pb2
          >>> api = config_service_v2_api.ConfigServiceV2Api()
          >>> sink_name = api.sink_path('[PROJECT]', '[SINK]')
          >>> sink = logging_config_pb2.LogSink()
          >>> response = api.update_sink(sink_name, sink)

        Args:
          sink_name (string): Required. The resource name of the sink to update, including the parent
            resource and the sink identifier.  If the sink does not exist, this method
            creates the sink.  Example: ``\"projects/my-project-id/sinks/my-sink-id\"``.
          sink (:class:`google.logging.v2.logging_config_pb2.LogSink`): Required. The updated sink, whose name is the same identifier that appears
            as part of ``sinkName``.  If ``sinkName`` does not exist, then
            this method creates a new sink.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.logging.v2.logging_config_pb2.LogSink` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = logging_config_pb2.UpdateSinkRequest(sink_name=sink_name,
                                                       sink=sink)
        return self._update_sink(request, options)

    def delete_sink(self, sink_name, options=None):
        """
        Deletes a sink.

        Example:
          >>> from google.cloud.gapic.logging.v2 import config_service_v2_api
          >>> api = config_service_v2_api.ConfigServiceV2Api()
          >>> sink_name = api.sink_path('[PROJECT]', '[SINK]')
          >>> api.delete_sink(sink_name)

        Args:
          sink_name (string): Required. The resource name of the sink to delete, including the parent
            resource and the sink identifier.  Example:
            ``\"projects/my-project-id/sinks/my-sink-id\"``.  It is an error if the sink
            does not exist.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = logging_config_pb2.DeleteSinkRequest(sink_name=sink_name)
        self._delete_sink(request, options)
class ErrorStatsServiceApi(object):
    """
    An API for retrieving and managing error statistics as well as data for
    individual events.
    """

    SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _CODE_GEN_NAME_VERSION = 'gapic/0.1.0'

    _GAX_VERSION = pkg_resources.get_distribution('google-gax').version

    _PAGE_DESCRIPTORS = {
        'list_group_stats':
        _PageDesc('page_token', 'next_page_token', 'error_group_stats'),
        'list_events':
        _PageDesc('page_token', 'next_page_token', 'error_events')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = ('https://www.googleapis.com/auth/cloud-platform', )

    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')

    @classmethod
    def project_path(cls, project):
        """Returns a fully-qualified project resource name string."""
        return cls._PROJECT_PATH_TEMPLATE.render({
            'project': project,
        })

    @classmethod
    def match_project_from_project_name(cls, project_name):
        """Parses the project from a project resource.

        Args:
          project_name (string): A fully-qualified path representing a project
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 metadata_transformer=None,
                 ssl_creds=None,
                 scopes=None,
                 client_config=None,
                 app_name='gax',
                 app_version=_GAX_VERSION):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          ssl_creds (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          metadata_transformer (Callable[[], list]): A function that creates
             the metadata for requests.
          app_name (string): The codename of the calling service.
          app_version (string): The version of the calling service.

        Returns:
          A ErrorStatsServiceApi object.
        """
        if scopes is None:
            scopes = self._ALL_SCOPES
        if client_config is None:
            client_config = {}
        goog_api_client = '{}/{} {} gax/{} python/{}'.format(
            app_name, app_version, self._CODE_GEN_NAME_VERSION,
            self._GAX_VERSION, platform.python_version())
        metadata = [('x-goog-api-client', goog_api_client)]
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'error_stats_service_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.devtools.clouderrorreporting.v1beta1.ErrorStatsService',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            kwargs={'metadata': metadata},
            page_descriptors=self._PAGE_DESCRIPTORS)
        self.error_stats_service_stub = config.create_stub(
            error_stats_service_pb2.ErrorStatsServiceStub,
            service_path,
            port,
            ssl_creds=ssl_creds,
            channel=channel,
            metadata_transformer=metadata_transformer,
            scopes=scopes)

        self._list_group_stats = api_callable.create_api_call(
            self.error_stats_service_stub.ListGroupStats,
            settings=defaults['list_group_stats'])
        self._list_events = api_callable.create_api_call(
            self.error_stats_service_stub.ListEvents,
            settings=defaults['list_events'])
        self._delete_events = api_callable.create_api_call(
            self.error_stats_service_stub.DeleteEvents,
            settings=defaults['delete_events'])

    # Service calls
    def list_group_stats(self,
                         project_name,
                         time_range,
                         group_id=None,
                         service_filter=None,
                         timed_count_duration=None,
                         alignment=None,
                         alignment_time=None,
                         order=None,
                         page_size=0,
                         options=None):
        """
        Lists the specified groups.

        Example:
          >>> from google.cloud.gapic.errorreporting.v1beta1 import error_stats_service_api
          >>> from google.devtools.clouderrorreporting.v1beta1 import error_stats_service_pb2
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = error_stats_service_api.ErrorStatsServiceApi()
          >>> project_name = api.project_path('[PROJECT]')
          >>> time_range = error_stats_service_pb2.QueryTimeRange()
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_group_stats(project_name, time_range):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_group_stats(project_name, time_range, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          project_name (string): [Required] The resource name of the Google Cloud Platform project. Written
            as <code>projects/</code> plus the
            <a href=\"https://support.google.com/cloud/answer/6158840\">Google Cloud
            Platform project ID</a>.

            Example: <code>projects/my-project-123</code>.
          group_id (list[string]): [Optional] List all <code>ErrorGroupStats</code> with these IDs.
          service_filter (:class:`google.devtools.clouderrorreporting.v1beta1.error_stats_service_pb2.ServiceContextFilter`): [Optional] List only <code>ErrorGroupStats</code> which belong to a service
            context that matches the filter.
            Data for all service contexts is returned if this field is not specified.
          time_range (:class:`google.devtools.clouderrorreporting.v1beta1.error_stats_service_pb2.QueryTimeRange`): [Required] List data for the given time range.
            Only <code>ErrorGroupStats</code> with a non-zero count in the given time
            range are returned, unless the request contains an explicit group_id list.
            If a group_id list is given, also <code>ErrorGroupStats</code> with zero
            occurrences are returned.
          timed_count_duration (:class:`google.protobuf.duration_pb2.Duration`): [Optional] The preferred duration for a single returned ``TimedCount``.
            If not set, no timed counts are returned.
          alignment (enum :class:`google.cloud.gapic.errorreporting.v1beta1.enums.TimedCountAlignment`): [Optional] The alignment of the timed counts to be returned.
            Default is ``ALIGNMENT_EQUAL_AT_END``.
          alignment_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): [Optional] Time where the timed counts shall be aligned if rounded
            alignment is chosen. Default is 00:00 UTC.
          order (enum :class:`google.cloud.gapic.errorreporting.v1beta1.enums.ErrorGroupOrder`): [Optional] The sort order in which the results are returned.
            Default is ``COUNT_DESC``.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.devtools.clouderrorreporting.v1beta1.error_stats_service_pb2.ErrorGroupStats` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        if group_id is None:
            group_id = []
        if service_filter is None:
            service_filter = error_stats_service_pb2.ServiceContextFilter()
        if timed_count_duration is None:
            timed_count_duration = duration_pb2.Duration()
        if alignment is None:
            alignment = enums.TimedCountAlignment.ERROR_COUNT_ALIGNMENT_UNSPECIFIED
        if alignment_time is None:
            alignment_time = timestamp_pb2.Timestamp()
        if order is None:
            order = enums.ErrorGroupOrder.GROUP_ORDER_UNSPECIFIED
        request = error_stats_service_pb2.ListGroupStatsRequest(
            project_name=project_name,
            time_range=time_range,
            group_id=group_id,
            service_filter=service_filter,
            timed_count_duration=timed_count_duration,
            alignment=alignment,
            alignment_time=alignment_time,
            order=order,
            page_size=page_size)
        return self._list_group_stats(request, options)

    def list_events(self,
                    project_name,
                    group_id,
                    service_filter=None,
                    time_range=None,
                    page_size=0,
                    options=None):
        """
        Lists the specified events.

        Example:
          >>> from google.cloud.gapic.errorreporting.v1beta1 import error_stats_service_api
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = error_stats_service_api.ErrorStatsServiceApi()
          >>> project_name = api.project_path('[PROJECT]')
          >>> group_id = ''
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_events(project_name, group_id):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_events(project_name, group_id, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          project_name (string): [Required] The resource name of the Google Cloud Platform project. Written
            as ``projects/`` plus the
            `Google Cloud Platform project ID <https://support.google.com/cloud/answer/6158840>`_.
            Example: ``projects/my-project-123``.
          group_id (string): [Required] The group for which events shall be returned.
          service_filter (:class:`google.devtools.clouderrorreporting.v1beta1.error_stats_service_pb2.ServiceContextFilter`): [Optional] List only ErrorGroups which belong to a service context that
            matches the filter.
            Data for all service contexts is returned if this field is not specified.
          time_range (:class:`google.devtools.clouderrorreporting.v1beta1.error_stats_service_pb2.QueryTimeRange`): [Optional] List only data for the given time range.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.devtools.clouderrorreporting.v1beta1.common_pb2.ErrorEvent` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        if service_filter is None:
            service_filter = error_stats_service_pb2.ServiceContextFilter()
        if time_range is None:
            time_range = error_stats_service_pb2.QueryTimeRange()
        request = error_stats_service_pb2.ListEventsRequest(
            project_name=project_name,
            group_id=group_id,
            service_filter=service_filter,
            time_range=time_range,
            page_size=page_size)
        return self._list_events(request, options)

    def delete_events(self, project_name, options=None):
        """
        Deletes all error events of a given project.

        Example:
          >>> from google.cloud.gapic.errorreporting.v1beta1 import error_stats_service_api
          >>> api = error_stats_service_api.ErrorStatsServiceApi()
          >>> project_name = api.project_path('[PROJECT]')
          >>> response = api.delete_events(project_name)

        Args:
          project_name (string): [Required] The resource name of the Google Cloud Platform project. Written
            as ``projects/`` plus the
            `Google Cloud Platform project ID <https://support.google.com/cloud/answer/6158840>`_.
            Example: ``projects/my-project-123``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = error_stats_service_pb2.DeleteEventsRequest(
            project_name=project_name)
        self._delete_events(request, options)
class ErrorStatsServiceClient(object):
    """
    An API for retrieving and managing error statistics as well as data for
    individual events.
    """

    SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _PAGE_DESCRIPTORS = {
        'list_group_stats':
        _PageDesc('page_token', 'next_page_token', 'error_group_stats'),
        'list_events':
        _PageDesc('page_token', 'next_page_token', 'error_events')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = ('https://www.googleapis.com/auth/cloud-platform', )

    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')

    @classmethod
    def project_path(cls, project):
        """Returns a fully-qualified project resource name string."""
        return cls._PROJECT_PATH_TEMPLATE.render({
            'project': project,
        })

    @classmethod
    def match_project_from_project_name(cls, project_name):
        """Parses the project from a project resource.

        Args:
          project_name (string): A fully-qualified path representing a project
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 credentials=None,
                 ssl_credentials=None,
                 scopes=None,
                 client_config=None,
                 app_name=None,
                 app_version='',
                 lib_name=None,
                 lib_version='',
                 metrics_headers=()):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          credentials (object): The authorization credentials to attach to
            requests. These credentials identify this application to the
            service.
          ssl_credentials (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          scopes (list[string]): A list of OAuth2 scopes to attach to requests.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          app_name (string): The name of the application calling
            the service. Recommended for analytics purposes.
          app_version (string): The version of the application calling
            the service. Recommended for analytics purposes.
          lib_name (string): The API library software used for calling
            the service. (Unless you are writing an API client itself,
            leave this as default.)
          lib_version (string): The API library software version used
            for calling the service. (Unless you are writing an API client
            itself, leave this as default.)
          metrics_headers (dict): A dictionary of values for tracking
            client library metrics. Ultimately serializes to a string
            (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be
            considered private.

        Returns:
          A ErrorStatsServiceClient object.
        """
        # Unless the calling application specifically requested
        # OAuth scopes, request everything.
        if scopes is None:
            scopes = self._ALL_SCOPES

        # Initialize an empty client config, if none is set.
        if client_config is None:
            client_config = {}

        # Initialize metrics_headers as an ordered dictionary
        # (cuts down on cardinality of the resulting string slightly).
        metrics_headers = collections.OrderedDict(metrics_headers)
        metrics_headers['gl-python'] = platform.python_version()

        # The library may or may not be set, depending on what is
        # calling this client. Newer client libraries set the library name
        # and version.
        if lib_name:
            metrics_headers[lib_name] = lib_version

        # Finally, track the GAPIC package version.
        metrics_headers['gapic'] = pkg_resources.get_distribution(
            'gapic-google-cloud-error-reporting-v1beta1', ).version

        # Load the configuration defaults.
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'error_stats_service_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.devtools.clouderrorreporting.v1beta1.ErrorStatsService',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            metrics_headers=metrics_headers,
            page_descriptors=self._PAGE_DESCRIPTORS,
        )
        self.error_stats_service_stub = config.create_stub(
            error_stats_service_pb2.ErrorStatsServiceStub,
            channel=channel,
            service_path=service_path,
            service_port=port,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)

        self._list_group_stats = api_callable.create_api_call(
            self.error_stats_service_stub.ListGroupStats,
            settings=defaults['list_group_stats'])
        self._list_events = api_callable.create_api_call(
            self.error_stats_service_stub.ListEvents,
            settings=defaults['list_events'])
        self._delete_events = api_callable.create_api_call(
            self.error_stats_service_stub.DeleteEvents,
            settings=defaults['delete_events'])

    # Service calls
    def list_group_stats(self,
                         project_name,
                         time_range,
                         group_id=None,
                         service_filter=None,
                         timed_count_duration=None,
                         alignment=None,
                         alignment_time=None,
                         order=None,
                         page_size=None,
                         options=None):
        """
        Lists the specified groups.

        Example:
          >>> from google.cloud.gapic.errorreporting.v1beta1 import error_stats_service_client
          >>> from google.cloud.proto.devtools.clouderrorreporting.v1beta1 import error_stats_service_pb2
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> client = error_stats_service_client.ErrorStatsServiceClient()
          >>> project_name = client.project_path('[PROJECT]')
          >>> time_range = error_stats_service_pb2.QueryTimeRange()
          >>>
          >>> # Iterate over all results
          >>> for element in client.list_group_stats(project_name, time_range):
          >>>     # process element
          >>>     pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in client.list_group_stats(project_name, time_range, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>     for element in page:
          >>>         # process element
          >>>         pass

        Args:
          project_name (string): [Required] The resource name of the Google Cloud Platform project. Written
            as <code>projects/</code> plus the
            <a href=\"https://support.google.com/cloud/answer/6158840\">Google Cloud
            Platform project ID</a>.

            Example: <code>projects/my-project-123</code>.
          time_range (:class:`google.cloud.proto.devtools.clouderrorreporting.v1beta1.error_stats_service_pb2.QueryTimeRange`): [Optional] List data for the given time range.
            If not set a default time range is used. The field time_range_begin
            in the response will specify the beginning of this time range.
            Only <code>ErrorGroupStats</code> with a non-zero count in the given time
            range are returned, unless the request contains an explicit group_id list.
            If a group_id list is given, also <code>ErrorGroupStats</code> with zero
            occurrences are returned.
          group_id (list[string]): [Optional] List all <code>ErrorGroupStats</code> with these IDs.
          service_filter (:class:`google.cloud.proto.devtools.clouderrorreporting.v1beta1.error_stats_service_pb2.ServiceContextFilter`): [Optional] List only <code>ErrorGroupStats</code> which belong to a service
            context that matches the filter.
            Data for all service contexts is returned if this field is not specified.
          timed_count_duration (:class:`google.protobuf.duration_pb2.Duration`): [Optional] The preferred duration for a single returned ``TimedCount``.
            If not set, no timed counts are returned.
          alignment (enum :class:`google.cloud.gapic.errorreporting.v1beta1.enums.TimedCountAlignment`): [Optional] The alignment of the timed counts to be returned.
            Default is ``ALIGNMENT_EQUAL_AT_END``.
          alignment_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): [Optional] Time where the timed counts shall be aligned if rounded
            alignment is chosen. Default is 00:00 UTC.
          order (enum :class:`google.cloud.gapic.errorreporting.v1beta1.enums.ErrorGroupOrder`): [Optional] The sort order in which the results are returned.
            Default is ``COUNT_DESC``.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.cloud.proto.devtools.clouderrorreporting.v1beta1.error_stats_service_pb2.ErrorGroupStats` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = error_stats_service_pb2.ListGroupStatsRequest(
            project_name=project_name,
            time_range=time_range,
            group_id=group_id,
            service_filter=service_filter,
            timed_count_duration=timed_count_duration,
            alignment=alignment,
            alignment_time=alignment_time,
            order=order,
            page_size=page_size)
        return self._list_group_stats(request, options)

    def list_events(self,
                    project_name,
                    group_id,
                    service_filter=None,
                    time_range=None,
                    page_size=None,
                    options=None):
        """
        Lists the specified events.

        Example:
          >>> from google.cloud.gapic.errorreporting.v1beta1 import error_stats_service_client
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> client = error_stats_service_client.ErrorStatsServiceClient()
          >>> project_name = client.project_path('[PROJECT]')
          >>> group_id = ''
          >>>
          >>> # Iterate over all results
          >>> for element in client.list_events(project_name, group_id):
          >>>     # process element
          >>>     pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in client.list_events(project_name, group_id, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>     for element in page:
          >>>         # process element
          >>>         pass

        Args:
          project_name (string): [Required] The resource name of the Google Cloud Platform project. Written
            as ``projects/`` plus the
            [Google Cloud Platform project
            ID](https://support.google.com/cloud/answer/6158840).
            Example: ``projects/my-project-123``.
          group_id (string): [Required] The group for which events shall be returned.
          service_filter (:class:`google.cloud.proto.devtools.clouderrorreporting.v1beta1.error_stats_service_pb2.ServiceContextFilter`): [Optional] List only ErrorGroups which belong to a service context that
            matches the filter.
            Data for all service contexts is returned if this field is not specified.
          time_range (:class:`google.cloud.proto.devtools.clouderrorreporting.v1beta1.error_stats_service_pb2.QueryTimeRange`): [Optional] List only data for the given time range.
            If not set a default time range is used. The field time_range_begin
            in the response will specify the beginning of this time range.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.cloud.proto.devtools.clouderrorreporting.v1beta1.common_pb2.ErrorEvent` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = error_stats_service_pb2.ListEventsRequest(
            project_name=project_name,
            group_id=group_id,
            service_filter=service_filter,
            time_range=time_range,
            page_size=page_size)
        return self._list_events(request, options)

    def delete_events(self, project_name, options=None):
        """
        Deletes all error events of a given project.

        Example:
          >>> from google.cloud.gapic.errorreporting.v1beta1 import error_stats_service_client
          >>> client = error_stats_service_client.ErrorStatsServiceClient()
          >>> project_name = client.project_path('[PROJECT]')
          >>> response = client.delete_events(project_name)

        Args:
          project_name (string): [Required] The resource name of the Google Cloud Platform project. Written
            as ``projects/`` plus the
            [Google Cloud Platform project
            ID](https://support.google.com/cloud/answer/6158840).
            Example: ``projects/my-project-123``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.devtools.clouderrorreporting.v1beta1.error_stats_service_pb2.DeleteEventsResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = error_stats_service_pb2.DeleteEventsRequest(
            project_name=project_name)
        return self._delete_events(request, options)
Exemple #26
0
class ConfigServiceV2Client(object):
    """
    Service for configuring sinks used to export log entries outside of
    Stackdriver Logging.
    """

    SERVICE_ADDRESS = 'logging.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _PAGE_DESCRIPTORS = {
        'list_sinks': _PageDesc('page_token', 'next_page_token', 'sinks')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = (
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/cloud-platform.read-only',
        'https://www.googleapis.com/auth/logging.admin',
        'https://www.googleapis.com/auth/logging.read',
        'https://www.googleapis.com/auth/logging.write',
    )

    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')
    _SINK_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/sinks/{sink}')

    @classmethod
    def project_path(cls, project):
        """Returns a fully-qualified project resource name string."""
        return cls._PROJECT_PATH_TEMPLATE.render({
            'project': project,
        })

    @classmethod
    def sink_path(cls, project, sink):
        """Returns a fully-qualified sink resource name string."""
        return cls._SINK_PATH_TEMPLATE.render({
            'project': project,
            'sink': sink,
        })

    @classmethod
    def match_project_from_project_name(cls, project_name):
        """Parses the project from a project resource.

        Args:
          project_name (string): A fully-qualified path representing a project
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')

    @classmethod
    def match_project_from_sink_name(cls, sink_name):
        """Parses the project from a sink resource.

        Args:
          sink_name (string): A fully-qualified path representing a sink
            resource.

        Returns:
          A string representing the project.
        """
        return cls._SINK_PATH_TEMPLATE.match(sink_name).get('project')

    @classmethod
    def match_sink_from_sink_name(cls, sink_name):
        """Parses the sink from a sink resource.

        Args:
          sink_name (string): A fully-qualified path representing a sink
            resource.

        Returns:
          A string representing the sink.
        """
        return cls._SINK_PATH_TEMPLATE.match(sink_name).get('sink')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 credentials=None,
                 ssl_credentials=None,
                 scopes=None,
                 client_config=None,
                 app_name=None,
                 app_version='',
                 lib_name=None,
                 lib_version='',
                 metrics_headers=()):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          credentials (object): The authorization credentials to attach to
            requests. These credentials identify this application to the
            service.
          ssl_credentials (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          scopes (list[string]): A list of OAuth2 scopes to attach to requests.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          app_name (string): The name of the application calling
            the service. Recommended for analytics purposes.
          app_version (string): The version of the application calling
            the service. Recommended for analytics purposes.
          lib_name (string): The API library software used for calling
            the service. (Unless you are writing an API client itself,
            leave this as default.)
          lib_version (string): The API library software version used
            for calling the service. (Unless you are writing an API client
            itself, leave this as default.)
          metrics_headers (dict): A dictionary of values for tracking
            client library metrics. Ultimately serializes to a string
            (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be
            considered private.

        Returns:
          A ConfigServiceV2Client object.
        """
        # Unless the calling application specifically requested
        # OAuth scopes, request everything.
        if scopes is None:
            scopes = self._ALL_SCOPES

        # Initialize an empty client config, if none is set.
        if client_config is None:
            client_config = {}

        # Initialize metrics_headers as an ordered dictionary
        # (cuts down on cardinality of the resulting string slightly).
        metrics_headers = collections.OrderedDict(metrics_headers)
        metrics_headers['gl-python'] = platform.python_version()

        # The library may or may not be set, depending on what is
        # calling this client. Newer client libraries set the library name
        # and version.
        if lib_name:
            metrics_headers[lib_name] = lib_version

        # Finally, track the GAPIC package version.
        metrics_headers['gapic'] = pkg_resources.get_distribution(
            'gapic-google-cloud-logging-v2', ).version

        # Load the configuration defaults.
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'config_service_v2_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.logging.v2.ConfigServiceV2',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            metrics_headers=metrics_headers,
            page_descriptors=self._PAGE_DESCRIPTORS,
        )
        self.config_service_v2_stub = config.create_stub(
            logging_config_pb2.ConfigServiceV2Stub,
            channel=channel,
            service_path=service_path,
            service_port=port,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)

        self._list_sinks = api_callable.create_api_call(
            self.config_service_v2_stub.ListSinks,
            settings=defaults['list_sinks'])
        self._get_sink = api_callable.create_api_call(
            self.config_service_v2_stub.GetSink, settings=defaults['get_sink'])
        self._create_sink = api_callable.create_api_call(
            self.config_service_v2_stub.CreateSink,
            settings=defaults['create_sink'])
        self._update_sink = api_callable.create_api_call(
            self.config_service_v2_stub.UpdateSink,
            settings=defaults['update_sink'])
        self._delete_sink = api_callable.create_api_call(
            self.config_service_v2_stub.DeleteSink,
            settings=defaults['delete_sink'])

    # Service calls
    def list_sinks(self, parent, page_size=0, options=None):
        """
        Lists sinks.

        Example:
          >>> from google.cloud.gapic.logging.v2 import config_service_v2_client
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = config_service_v2_client.ConfigServiceV2Client()
          >>> parent = api.project_path('[PROJECT]')
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_sinks(parent):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_sinks(parent, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          parent (string): Required. The parent resource whose sinks are to be listed.
            Examples: ``\"projects/my-logging-project\"``, ``\"organizations/123456789\"``.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.cloud.proto.logging.v2.logging_config_pb2.LogSink` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = logging_config_pb2.ListSinksRequest(parent=parent,
                                                      page_size=page_size)
        return self._list_sinks(request, options)

    def get_sink(self, sink_name, options=None):
        """
        Gets a sink.

        Example:
          >>> from google.cloud.gapic.logging.v2 import config_service_v2_client
          >>> api = config_service_v2_client.ConfigServiceV2Client()
          >>> sink_name = api.sink_path('[PROJECT]', '[SINK]')
          >>> response = api.get_sink(sink_name)

        Args:
          sink_name (string): Required. The parent resource name of the sink:

            ::

                \"projects/[PROJECT_ID]/sinks/[SINK_ID]\"
                \"organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]\"

            Example: ``\"projects/my-project-id/sinks/my-sink-id\"``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.logging.v2.logging_config_pb2.LogSink` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = logging_config_pb2.GetSinkRequest(sink_name=sink_name)
        return self._get_sink(request, options)

    def create_sink(self,
                    parent,
                    sink,
                    unique_writer_identity=False,
                    options=None):
        """
        Creates a sink that exports specified log entries to a destination.  The
        export of newly-ingested log entries begins immediately, unless the current
        time is outside the sink's start and end times or the sink's
        ``writer_identity`` is not permitted to write to the destination.  A sink can
        export log entries only from the resource owning the sink.

        Example:
          >>> from google.cloud.gapic.logging.v2 import config_service_v2_client
          >>> from google.cloud.proto.logging.v2 import logging_config_pb2
          >>> api = config_service_v2_client.ConfigServiceV2Client()
          >>> parent = api.project_path('[PROJECT]')
          >>> sink = logging_config_pb2.LogSink()
          >>> response = api.create_sink(parent, sink)

        Args:
          parent (string): Required. The resource in which to create the sink:

            ::

                \"projects/[PROJECT_ID]\"
                \"organizations/[ORGANIZATION_ID]\"

            Examples: ``\"projects/my-logging-project\"``, ``\"organizations/123456789\"``.
          sink (:class:`google.cloud.proto.logging.v2.logging_config_pb2.LogSink`): Required. The new sink, whose ``name`` parameter is a sink identifier that
            is not already in use.
          unique_writer_identity (bool): Optional. Determines the kind of IAM identity returned as ``writer_identity``
            in the new sink.  If this value is omitted or set to false, and if the
            sink's parent is a project, then the value returned as ``writer_identity`` is
            ``[email protected]``, the same identity used before the addition of
            writer identities to this API. The sink's destination must be in the same
            project as the sink itself.

            If this field is set to true, or if the sink is owned by a non-project
            resource such as an organization, then the value of ``writer_identity`` will
            be a unique service account used only for exports from the new sink.  For
            more information, see ``writer_identity`` in ``LogSink``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.logging.v2.logging_config_pb2.LogSink` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = logging_config_pb2.CreateSinkRequest(
            parent=parent,
            sink=sink,
            unique_writer_identity=unique_writer_identity)
        return self._create_sink(request, options)

    def update_sink(self,
                    sink_name,
                    sink,
                    unique_writer_identity=False,
                    options=None):
        """
        Updates a sink. If the named sink doesn't exist, then this method is
        identical to
        `sinks.create <https://cloud.google.com/logging/docs/api/reference/rest/v2/projects.sinks/create>`_.
        If the named sink does exist, then this method replaces the following
        fields in the existing sink with values from the new sink: ``destination``,
        ``filter``, ``output_version_format``, ``start_time``, and ``end_time``.
        The updated filter might also have a new ``writer_identity``; see the
        ``unique_writer_identity`` field.

        Example:
          >>> from google.cloud.gapic.logging.v2 import config_service_v2_client
          >>> from google.cloud.proto.logging.v2 import logging_config_pb2
          >>> api = config_service_v2_client.ConfigServiceV2Client()
          >>> sink_name = api.sink_path('[PROJECT]', '[SINK]')
          >>> sink = logging_config_pb2.LogSink()
          >>> response = api.update_sink(sink_name, sink)

        Args:
          sink_name (string): Required. The full resource name of the sink to update, including the
            parent resource and the sink identifier:

            ::

                \"projects/[PROJECT_ID]/sinks/[SINK_ID]\"
                \"organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]\"

            Example: ``\"projects/my-project-id/sinks/my-sink-id\"``.
          sink (:class:`google.cloud.proto.logging.v2.logging_config_pb2.LogSink`): Required. The updated sink, whose name is the same identifier that appears
            as part of ``sink_name``.  If ``sink_name`` does not exist, then
            this method creates a new sink.
          unique_writer_identity (bool): Optional. See
            `sinks.create <https://cloud.google.com/logging/docs/api/reference/rest/v2/projects.sinks/create>`_
            for a description of this field.  When updating a sink, the effect of this
            field on the value of ``writer_identity`` in the updated sink depends on both
            the old and new values of this field:

            +   If the old and new values of this field are both false or both true,
            ::

                then there is no change to the sink's `writer_identity`.
            +   If the old value was false and the new value is true, then
            ::

                `writer_identity` is changed to a unique service account.
            +   It is an error if the old value was true and the new value is false.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.logging.v2.logging_config_pb2.LogSink` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = logging_config_pb2.UpdateSinkRequest(
            sink_name=sink_name,
            sink=sink,
            unique_writer_identity=unique_writer_identity)
        return self._update_sink(request, options)

    def delete_sink(self, sink_name, options=None):
        """
        Deletes a sink. If the sink has a unique ``writer_identity``, then that
        service account is also deleted.

        Example:
          >>> from google.cloud.gapic.logging.v2 import config_service_v2_client
          >>> api = config_service_v2_client.ConfigServiceV2Client()
          >>> sink_name = api.sink_path('[PROJECT]', '[SINK]')
          >>> api.delete_sink(sink_name)

        Args:
          sink_name (string): Required. The full resource name of the sink to delete, including the
            parent resource and the sink identifier:

            ::

                \"projects/[PROJECT_ID]/sinks/[SINK_ID]\"
                \"organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]\"

            It is an error if the sink does not exist.  Example:
            ``\"projects/my-project-id/sinks/my-sink-id\"``.  It is an error if
            the sink does not exist.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = logging_config_pb2.DeleteSinkRequest(sink_name=sink_name)
        self._delete_sink(request, options)
class SubscriberClient(object):
    """
    The service that an application uses to manipulate subscriptions and to
    consume messages from a subscription via the ``Pull`` method.
    """

    SERVICE_ADDRESS = 'pubsub.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _PAGE_DESCRIPTORS = {
        'list_subscriptions':
        _PageDesc('page_token', 'next_page_token', 'subscriptions'),
        'list_snapshots':
        _PageDesc('page_token', 'next_page_token', 'snapshots')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = (
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/pubsub',
    )

    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')
    _SNAPSHOT_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/snapshots/{snapshot}')
    _SUBSCRIPTION_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/subscriptions/{subscription}')
    _TOPIC_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/topics/{topic}')

    @classmethod
    def project_path(cls, project):
        """Returns a fully-qualified project resource name string."""
        return cls._PROJECT_PATH_TEMPLATE.render({
            'project': project,
        })

    @classmethod
    def snapshot_path(cls, project, snapshot):
        """Returns a fully-qualified snapshot resource name string."""
        return cls._SNAPSHOT_PATH_TEMPLATE.render({
            'project': project,
            'snapshot': snapshot,
        })

    @classmethod
    def subscription_path(cls, project, subscription):
        """Returns a fully-qualified subscription resource name string."""
        return cls._SUBSCRIPTION_PATH_TEMPLATE.render({
            'project':
            project,
            'subscription':
            subscription,
        })

    @classmethod
    def topic_path(cls, project, topic):
        """Returns a fully-qualified topic resource name string."""
        return cls._TOPIC_PATH_TEMPLATE.render({
            'project': project,
            'topic': topic,
        })

    @classmethod
    def match_project_from_project_name(cls, project_name):
        """Parses the project from a project resource.

        Args:
          project_name (string): A fully-qualified path representing a project
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')

    @classmethod
    def match_project_from_snapshot_name(cls, snapshot_name):
        """Parses the project from a snapshot resource.

        Args:
          snapshot_name (string): A fully-qualified path representing a snapshot
            resource.

        Returns:
          A string representing the project.
        """
        return cls._SNAPSHOT_PATH_TEMPLATE.match(snapshot_name).get('project')

    @classmethod
    def match_snapshot_from_snapshot_name(cls, snapshot_name):
        """Parses the snapshot from a snapshot resource.

        Args:
          snapshot_name (string): A fully-qualified path representing a snapshot
            resource.

        Returns:
          A string representing the snapshot.
        """
        return cls._SNAPSHOT_PATH_TEMPLATE.match(snapshot_name).get('snapshot')

    @classmethod
    def match_project_from_subscription_name(cls, subscription_name):
        """Parses the project from a subscription resource.

        Args:
          subscription_name (string): A fully-qualified path representing a subscription
            resource.

        Returns:
          A string representing the project.
        """
        return cls._SUBSCRIPTION_PATH_TEMPLATE.match(subscription_name).get(
            'project')

    @classmethod
    def match_subscription_from_subscription_name(cls, subscription_name):
        """Parses the subscription from a subscription resource.

        Args:
          subscription_name (string): A fully-qualified path representing a subscription
            resource.

        Returns:
          A string representing the subscription.
        """
        return cls._SUBSCRIPTION_PATH_TEMPLATE.match(subscription_name).get(
            'subscription')

    @classmethod
    def match_project_from_topic_name(cls, topic_name):
        """Parses the project from a topic resource.

        Args:
          topic_name (string): A fully-qualified path representing a topic
            resource.

        Returns:
          A string representing the project.
        """
        return cls._TOPIC_PATH_TEMPLATE.match(topic_name).get('project')

    @classmethod
    def match_topic_from_topic_name(cls, topic_name):
        """Parses the topic from a topic resource.

        Args:
          topic_name (string): A fully-qualified path representing a topic
            resource.

        Returns:
          A string representing the topic.
        """
        return cls._TOPIC_PATH_TEMPLATE.match(topic_name).get('topic')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 credentials=None,
                 ssl_credentials=None,
                 scopes=None,
                 client_config=None,
                 app_name=None,
                 app_version='',
                 lib_name=None,
                 lib_version='',
                 metrics_headers=()):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          credentials (object): The authorization credentials to attach to
            requests. These credentials identify this application to the
            service.
          ssl_credentials (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          scopes (list[string]): A list of OAuth2 scopes to attach to requests.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          app_name (string): The name of the application calling
            the service. Recommended for analytics purposes.
          app_version (string): The version of the application calling
            the service. Recommended for analytics purposes.
          lib_name (string): The API library software used for calling
            the service. (Unless you are writing an API client itself,
            leave this as default.)
          lib_version (string): The API library software version used
            for calling the service. (Unless you are writing an API client
            itself, leave this as default.)
          metrics_headers (dict): A dictionary of values for tracking
            client library metrics. Ultimately serializes to a string
            (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be
            considered private.

        Returns:
          A SubscriberClient object.
        """
        # Unless the calling application specifically requested
        # OAuth scopes, request everything.
        if scopes is None:
            scopes = self._ALL_SCOPES

        # Initialize an empty client config, if none is set.
        if client_config is None:
            client_config = {}

        # Initialize metrics_headers as an ordered dictionary
        # (cuts down on cardinality of the resulting string slightly).
        metrics_headers = collections.OrderedDict(metrics_headers)
        metrics_headers['gl-python'] = platform.python_version()

        # The library may or may not be set, depending on what is
        # calling this client. Newer client libraries set the library name
        # and version.
        if lib_name:
            metrics_headers[lib_name] = lib_version

        # Finally, track the GAPIC package version.
        metrics_headers['gapic'] = pkg_resources.get_distribution(
            'google-cloud-pubsub', ).version

        # Load the configuration defaults.
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'subscriber_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.pubsub.v1.Subscriber',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            metrics_headers=metrics_headers,
            page_descriptors=self._PAGE_DESCRIPTORS,
        )
        self.iam_policy_stub = config.create_stub(
            iam_policy_pb2.IAMPolicyStub,
            channel=channel,
            service_path=service_path,
            service_port=port,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)
        self.subscriber_stub = config.create_stub(
            pubsub_pb2.SubscriberStub,
            channel=channel,
            service_path=service_path,
            service_port=port,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)

        self._create_subscription = api_callable.create_api_call(
            self.subscriber_stub.CreateSubscription,
            settings=defaults['create_subscription'])
        self._get_subscription = api_callable.create_api_call(
            self.subscriber_stub.GetSubscription,
            settings=defaults['get_subscription'])
        self._update_subscription = api_callable.create_api_call(
            self.subscriber_stub.UpdateSubscription,
            settings=defaults['update_subscription'])
        self._list_subscriptions = api_callable.create_api_call(
            self.subscriber_stub.ListSubscriptions,
            settings=defaults['list_subscriptions'])
        self._delete_subscription = api_callable.create_api_call(
            self.subscriber_stub.DeleteSubscription,
            settings=defaults['delete_subscription'])
        self._modify_ack_deadline = api_callable.create_api_call(
            self.subscriber_stub.ModifyAckDeadline,
            settings=defaults['modify_ack_deadline'])
        self._acknowledge = api_callable.create_api_call(
            self.subscriber_stub.Acknowledge, settings=defaults['acknowledge'])
        self._pull = api_callable.create_api_call(self.subscriber_stub.Pull,
                                                  settings=defaults['pull'])
        self._streaming_pull = api_callable.create_api_call(
            self.subscriber_stub.StreamingPull,
            settings=defaults['streaming_pull'])
        self._modify_push_config = api_callable.create_api_call(
            self.subscriber_stub.ModifyPushConfig,
            settings=defaults['modify_push_config'])
        self._list_snapshots = api_callable.create_api_call(
            self.subscriber_stub.ListSnapshots,
            settings=defaults['list_snapshots'])
        self._create_snapshot = api_callable.create_api_call(
            self.subscriber_stub.CreateSnapshot,
            settings=defaults['create_snapshot'])
        self._delete_snapshot = api_callable.create_api_call(
            self.subscriber_stub.DeleteSnapshot,
            settings=defaults['delete_snapshot'])
        self._seek = api_callable.create_api_call(self.subscriber_stub.Seek,
                                                  settings=defaults['seek'])
        self._set_iam_policy = api_callable.create_api_call(
            self.iam_policy_stub.SetIamPolicy,
            settings=defaults['set_iam_policy'])
        self._get_iam_policy = api_callable.create_api_call(
            self.iam_policy_stub.GetIamPolicy,
            settings=defaults['get_iam_policy'])
        self._test_iam_permissions = api_callable.create_api_call(
            self.iam_policy_stub.TestIamPermissions,
            settings=defaults['test_iam_permissions'])

    # Service calls
    def create_subscription(self,
                            name,
                            topic,
                            push_config=None,
                            ack_deadline_seconds=None,
                            retain_acked_messages=None,
                            message_retention_duration=None,
                            options=None):
        """
        Creates a subscription to a given topic.
        If the subscription already exists, returns ``ALREADY_EXISTS``.
        If the corresponding topic doesn't exist, returns ``NOT_FOUND``.

        If the name is not provided in the request, the server will assign a random
        name for this subscription on the same project as the topic, conforming
        to the
        `resource name format <https://cloud.google.com/pubsub/docs/overview#names>`_.
        The generated name is populated in the returned Subscription object.
        Note that for REST API requests, you must specify a name in the request.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_client
          >>> client = subscriber_client.SubscriberClient()
          >>> name = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> topic = client.topic_path('[PROJECT]', '[TOPIC]')
          >>> response = client.create_subscription(name, topic)

        Args:
          name (string): The name of the subscription. It must have the format
            ``\"projects/{project}/subscriptions/{subscription}\"``. ``{subscription}`` must
            start with a letter, and contain only letters (``[A-Za-z]``), numbers
            (``[0-9]``), dashes (``-``), underscores (``_``), periods (``.``), tildes (``~``),
            plus (``+``) or percent signs (``%``). It must be between 3 and 255 characters
            in length, and it must not start with ``\"goog\"``.
          topic (string): The name of the topic from which this subscription is receiving messages.
            Format is ``projects/{project}/topics/{topic}``.
            The value of this field will be ``_deleted-topic_`` if the topic has been
            deleted.
          push_config (:class:`google.cloud.proto.pubsub.v1.pubsub_pb2.PushConfig`): If push delivery is used with this subscription, this field is
            used to configure it. An empty ``pushConfig`` signifies that the subscriber
            will pull and ack messages using API methods.
          ack_deadline_seconds (int): This value is the maximum time after a subscriber receives a message
            before the subscriber should acknowledge the message. After message
            delivery but before the ack deadline expires and before the message is
            acknowledged, it is an outstanding message and will not be delivered
            again during that time (on a best-effort basis).

            For pull subscriptions, this value is used as the initial value for the ack
            deadline. To override this value for a given message, call
            ``ModifyAckDeadline`` with the corresponding ``ack_id`` if using
            pull.
            The minimum custom deadline you can specify is 10 seconds.
            The maximum custom deadline you can specify is 600 seconds (10 minutes).
            If this parameter is 0, a default value of 10 seconds is used.

            For push delivery, this value is also used to set the request timeout for
            the call to the push endpoint.

            If the subscriber never acknowledges the message, the Pub/Sub
            system will eventually redeliver the message.
          retain_acked_messages (bool): Indicates whether to retain acknowledged messages. If true, then
            messages are not expunged from the subscription's backlog, even if they are
            acknowledged, until they fall out of the ``message_retention_duration``
            window.
          message_retention_duration (:class:`google.protobuf.duration_pb2.Duration`): How long to retain unacknowledged messages in the subscription's backlog,
            from the moment a message is published.
            If ``retain_acked_messages`` is true, then this also configures the retention
            of acknowledged messages, and thus configures how far back in time a ``Seek``
            can be done. Defaults to 7 days. Cannot be more than 7 days or less than 10
            minutes.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Subscription` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = pubsub_pb2.Subscription(
            name=name,
            topic=topic,
            push_config=push_config,
            ack_deadline_seconds=ack_deadline_seconds,
            retain_acked_messages=retain_acked_messages,
            message_retention_duration=message_retention_duration)
        return self._create_subscription(request, options)

    def get_subscription(self, subscription, options=None):
        """
        Gets the configuration details of a subscription.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_client
          >>> client = subscriber_client.SubscriberClient()
          >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> response = client.get_subscription(subscription)

        Args:
          subscription (string): The name of the subscription to get.
            Format is ``projects/{project}/subscriptions/{sub}``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Subscription` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = pubsub_pb2.GetSubscriptionRequest(subscription=subscription)
        return self._get_subscription(request, options)

    def update_subscription(self, subscription, update_mask, options=None):
        """
        Updates an existing subscription. Note that certain properties of a
        subscription, such as its topic, are not modifiable.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_client
          >>> from google.cloud.proto.pubsub.v1 import pubsub_pb2
          >>> from google.protobuf import field_mask_pb2
          >>> client = subscriber_client.SubscriberClient()
          >>> subscription = pubsub_pb2.Subscription()
          >>> update_mask = field_mask_pb2.FieldMask()
          >>> response = client.update_subscription(subscription, update_mask)

        Args:
          subscription (:class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Subscription`): The updated subscription object.
          update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): Indicates which fields in the provided subscription to update.
            Must be specified and non-empty.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Subscription` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = pubsub_pb2.UpdateSubscriptionRequest(
            subscription=subscription, update_mask=update_mask)
        return self._update_subscription(request, options)

    def list_subscriptions(self, project, page_size=None, options=None):
        """
        Lists matching subscriptions.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_client
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> client = subscriber_client.SubscriberClient()
          >>> project = client.project_path('[PROJECT]')
          >>>
          >>> # Iterate over all results
          >>> for element in client.list_subscriptions(project):
          >>>     # process element
          >>>     pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in client.list_subscriptions(project, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>     for element in page:
          >>>         # process element
          >>>         pass

        Args:
          project (string): The name of the cloud project that subscriptions belong to.
            Format is ``projects/{project}``.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Subscription` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = pubsub_pb2.ListSubscriptionsRequest(project=project,
                                                      page_size=page_size)
        return self._list_subscriptions(request, options)

    def delete_subscription(self, subscription, options=None):
        """
        Deletes an existing subscription. All messages retained in the subscription
        are immediately dropped. Calls to ``Pull`` after deletion will return
        ``NOT_FOUND``. After a subscription is deleted, a new one may be created with
        the same name, but the new one has no association with the old
        subscription or its topic unless the same topic is specified.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_client
          >>> client = subscriber_client.SubscriberClient()
          >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> client.delete_subscription(subscription)

        Args:
          subscription (string): The subscription to delete.
            Format is ``projects/{project}/subscriptions/{sub}``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = pubsub_pb2.DeleteSubscriptionRequest(
            subscription=subscription)
        self._delete_subscription(request, options)

    def modify_ack_deadline(self,
                            subscription,
                            ack_ids,
                            ack_deadline_seconds,
                            options=None):
        """
        Modifies the ack deadline for a specific message. This method is useful
        to indicate that more time is needed to process a message by the
        subscriber, or to make the message available for redelivery if the
        processing was interrupted. Note that this does not modify the
        subscription-level ``ackDeadlineSeconds`` used for subsequent messages.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_client
          >>> client = subscriber_client.SubscriberClient()
          >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> ack_ids = []
          >>> ack_deadline_seconds = 0
          >>> client.modify_ack_deadline(subscription, ack_ids, ack_deadline_seconds)

        Args:
          subscription (string): The name of the subscription.
            Format is ``projects/{project}/subscriptions/{sub}``.
          ack_ids (list[string]): List of acknowledgment IDs.
          ack_deadline_seconds (int): The new ack deadline with respect to the time this request was sent to
            the Pub/Sub system. For example, if the value is 10, the new
            ack deadline will expire 10 seconds after the ``ModifyAckDeadline`` call
            was made. Specifying zero may immediately make the message available for
            another pull request.
            The minimum deadline you can specify is 0 seconds.
            The maximum deadline you can specify is 600 seconds (10 minutes).
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = pubsub_pb2.ModifyAckDeadlineRequest(
            subscription=subscription,
            ack_ids=ack_ids,
            ack_deadline_seconds=ack_deadline_seconds)
        self._modify_ack_deadline(request, options)

    def acknowledge(self, subscription, ack_ids, options=None):
        """
        Acknowledges the messages associated with the ``ack_ids`` in the
        ``AcknowledgeRequest``. The Pub/Sub system can remove the relevant messages
        from the subscription.

        Acknowledging a message whose ack deadline has expired may succeed,
        but such a message may be redelivered later. Acknowledging a message more
        than once will not result in an error.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_client
          >>> client = subscriber_client.SubscriberClient()
          >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> ack_ids = []
          >>> client.acknowledge(subscription, ack_ids)

        Args:
          subscription (string): The subscription whose message is being acknowledged.
            Format is ``projects/{project}/subscriptions/{sub}``.
          ack_ids (list[string]): The acknowledgment ID for the messages being acknowledged that was returned
            by the Pub/Sub system in the ``Pull`` response. Must not be empty.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = pubsub_pb2.AcknowledgeRequest(subscription=subscription,
                                                ack_ids=ack_ids)
        self._acknowledge(request, options)

    def pull(self,
             subscription,
             max_messages,
             return_immediately=None,
             options=None):
        """
        Pulls messages from the server. Returns an empty list if there are no
        messages available in the backlog. The server may return ``UNAVAILABLE`` if
        there are too many concurrent pull requests pending for the given
        subscription.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_client
          >>> client = subscriber_client.SubscriberClient()
          >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> max_messages = 0
          >>> response = client.pull(subscription, max_messages)

        Args:
          subscription (string): The subscription from which messages should be pulled.
            Format is ``projects/{project}/subscriptions/{sub}``.
          max_messages (int): The maximum number of messages returned for this request. The Pub/Sub
            system may return fewer than the number specified.
          return_immediately (bool): If this field set to true, the system will respond immediately even if
            it there are no messages available to return in the ``Pull`` response.
            Otherwise, the system may wait (for a bounded amount of time) until at
            least one message is available, rather than returning no messages. The
            client may cancel the request if it does not wish to wait any longer for
            the response.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.PullResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = pubsub_pb2.PullRequest(subscription=subscription,
                                         max_messages=max_messages,
                                         return_immediately=return_immediately)
        return self._pull(request, options)

    def streaming_pull(self, requests, options=None):
        """
        (EXPERIMENTAL) StreamingPull is an experimental feature. This RPC will
        respond with UNIMPLEMENTED errors unless you have been invited to test
        this feature. Contact [email protected] with any questions.

        Establishes a stream with the server, which sends messages down to the
        client. The client streams acknowledgements and ack deadline modifications
        back to the server. The server will close the stream and return the status
        on any error. The server may close the stream with status ``OK`` to reassign
        server-side resources, in which case, the client should re-establish the
        stream. ``UNAVAILABLE`` may also be returned in the case of a transient error
        (e.g., a server restart). These should also be retried by the client. Flow
        control can be achieved by configuring the underlying RPC channel.

        EXPERIMENTAL: This method interface might change in the future.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_client
          >>> from google.cloud.proto.pubsub.v1 import pubsub_pb2
          >>> client = subscriber_client.SubscriberClient()
          >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> stream_ack_deadline_seconds = 0
          >>> request = pubsub_pb2.StreamingPullRequest(subscription=subscription, stream_ack_deadline_seconds=stream_ack_deadline_seconds)
          >>> requests = [request]
          >>> for element in client.streaming_pull(requests):
          >>>     # process element
          >>>     pass

        Args:
          requests (iterator[:class:`google.cloud.proto.pubsub.v1.pubsub_pb2.StreamingPullRequest`]): The input objects.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          iterator[:class:`google.cloud.proto.pubsub.v1.pubsub_pb2.StreamingPullResponse`].

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        return self._streaming_pull(requests, options)

    def modify_push_config(self, subscription, push_config, options=None):
        """
        Modifies the ``PushConfig`` for a specified subscription.

        This may be used to change a push subscription to a pull one (signified by
        an empty ``PushConfig``) or vice versa, or change the endpoint URL and other
        attributes of a push subscription. Messages will accumulate for delivery
        continuously through the call regardless of changes to the ``PushConfig``.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_client
          >>> from google.cloud.proto.pubsub.v1 import pubsub_pb2
          >>> client = subscriber_client.SubscriberClient()
          >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> push_config = pubsub_pb2.PushConfig()
          >>> client.modify_push_config(subscription, push_config)

        Args:
          subscription (string): The name of the subscription.
            Format is ``projects/{project}/subscriptions/{sub}``.
          push_config (:class:`google.cloud.proto.pubsub.v1.pubsub_pb2.PushConfig`): The push configuration for future deliveries.

            An empty ``pushConfig`` indicates that the Pub/Sub system should
            stop pushing messages from the given subscription and allow
            messages to be pulled and acknowledged - effectively pausing
            the subscription if ``Pull`` is not called.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = pubsub_pb2.ModifyPushConfigRequest(subscription=subscription,
                                                     push_config=push_config)
        self._modify_push_config(request, options)

    def list_snapshots(self, project, page_size=None, options=None):
        """
        Lists the existing snapshots.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_client
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> client = subscriber_client.SubscriberClient()
          >>> project = client.project_path('[PROJECT]')
          >>>
          >>> # Iterate over all results
          >>> for element in client.list_snapshots(project):
          >>>     # process element
          >>>     pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in client.list_snapshots(project, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>     for element in page:
          >>>         # process element
          >>>         pass

        Args:
          project (string): The name of the cloud project that snapshots belong to.
            Format is ``projects/{project}``.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Snapshot` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = pubsub_pb2.ListSnapshotsRequest(project=project,
                                                  page_size=page_size)
        return self._list_snapshots(request, options)

    def create_snapshot(self, name, subscription, options=None):
        """
        Creates a snapshot from the requested subscription.
        If the snapshot already exists, returns ``ALREADY_EXISTS``.
        If the requested subscription doesn't exist, returns ``NOT_FOUND``.

        If the name is not provided in the request, the server will assign a random
        name for this snapshot on the same project as the subscription, conforming
        to the
        `resource name format <https://cloud.google.com/pubsub/docs/overview#names>`_.
        The generated name is populated in the returned Snapshot object.
        Note that for REST API requests, you must specify a name in the request.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_client
          >>> client = subscriber_client.SubscriberClient()
          >>> name = client.snapshot_path('[PROJECT]', '[SNAPSHOT]')
          >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> response = client.create_snapshot(name, subscription)

        Args:
          name (string): Optional user-provided name for this snapshot.
            If the name is not provided in the request, the server will assign a random
            name for this snapshot on the same project as the subscription.
            Note that for REST API requests, you must specify a name.
            Format is ``projects/{project}/snapshots/{snap}``.
          subscription (string): The subscription whose backlog the snapshot retains.
            Specifically, the created snapshot is guaranteed to retain:

               - The existing backlog on the subscription. More precisely, this is
                 defined as the messages in the subscription's backlog that are
                 unacknowledged upon the successful completion of the
                 `CreateSnapshot` request; as well as:
               - Any messages published to the subscription's topic following the
                 successful completion of the CreateSnapshot request.

            Format is ``projects/{project}/subscriptions/{sub}``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Snapshot` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = pubsub_pb2.CreateSnapshotRequest(name=name,
                                                   subscription=subscription)
        return self._create_snapshot(request, options)

    def delete_snapshot(self, snapshot, options=None):
        """
        Removes an existing snapshot. All messages retained in the snapshot
        are immediately dropped. After a snapshot is deleted, a new one may be
        created with the same name, but the new one has no association with the old
        snapshot or its subscription, unless the same subscription is specified.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_client
          >>> client = subscriber_client.SubscriberClient()
          >>> snapshot = client.snapshot_path('[PROJECT]', '[SNAPSHOT]')
          >>> client.delete_snapshot(snapshot)

        Args:
          snapshot (string): The name of the snapshot to delete.
            Format is ``projects/{project}/snapshots/{snap}``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = pubsub_pb2.DeleteSnapshotRequest(snapshot=snapshot)
        self._delete_snapshot(request, options)

    def seek(self, subscription, time=None, snapshot=None, options=None):
        """
        Seeks an existing subscription to a point in time or to a given snapshot,
        whichever is provided in the request.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_client
          >>> client = subscriber_client.SubscriberClient()
          >>> subscription = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> response = client.seek(subscription)

        Args:
          subscription (string): The subscription to affect.
          time (:class:`google.protobuf.timestamp_pb2.Timestamp`): The time to seek to.
            Messages retained in the subscription that were published before this
            time are marked as acknowledged, and messages retained in the
            subscription that were published after this time are marked as
            unacknowledged. Note that this operation affects only those messages
            retained in the subscription (configured by the combination of
            ``message_retention_duration`` and ``retain_acked_messages``). For example,
            if ``time`` corresponds to a point before the message retention
            window (or to a point before the system's notion of the subscription
            creation time), only retained messages will be marked as unacknowledged,
            and already-expunged messages will not be restored.
          snapshot (string): The snapshot to seek to. The snapshot's topic must be the same as that of
            the provided subscription.
            Format is ``projects/{project}/snapshots/{snap}``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.SeekResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Sanity check: We have some fields which are mutually exclusive;
        # raise ValueError if more than one is sent.
        oneof.check_oneof(
            time=time,
            snapshot=snapshot,
        )

        # Create the request object.
        request = pubsub_pb2.SeekRequest(subscription=subscription,
                                         time=time,
                                         snapshot=snapshot)
        return self._seek(request, options)

    def set_iam_policy(self, resource, policy, options=None):
        """
        Sets the access control policy on the specified resource. Replaces any
        existing policy.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_client
          >>> from google.iam.v1 import policy_pb2
          >>> client = subscriber_client.SubscriberClient()
          >>> resource = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> policy = policy_pb2.Policy()
          >>> response = client.set_iam_policy(resource, policy)

        Args:
          resource (string): REQUIRED: The resource for which the policy is being specified.
            ``resource`` is usually specified as a path. For example, a Project
            resource is specified as ``projects/{project}``.
          policy (:class:`google.iam.v1.policy_pb2.Policy`): REQUIRED: The complete policy to be applied to the ``resource``. The size of
            the policy is limited to a few 10s of KB. An empty policy is a
            valid policy but certain Cloud Platform services (such as Projects)
            might reject them.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.v1.policy_pb2.Policy` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = iam_policy_pb2.SetIamPolicyRequest(resource=resource,
                                                     policy=policy)
        return self._set_iam_policy(request, options)

    def get_iam_policy(self, resource, options=None):
        """
        Gets the access control policy for a resource.
        Returns an empty policy if the resource exists and does not have a policy
        set.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_client
          >>> client = subscriber_client.SubscriberClient()
          >>> resource = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> response = client.get_iam_policy(resource)

        Args:
          resource (string): REQUIRED: The resource for which the policy is being requested.
            ``resource`` is usually specified as a path. For example, a Project
            resource is specified as ``projects/{project}``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.v1.policy_pb2.Policy` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = iam_policy_pb2.GetIamPolicyRequest(resource=resource)
        return self._get_iam_policy(request, options)

    def test_iam_permissions(self, resource, permissions, options=None):
        """
        Returns permissions that a caller has on the specified resource.
        If the resource does not exist, this will return an empty set of
        permissions, not a NOT_FOUND error.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import subscriber_client
          >>> client = subscriber_client.SubscriberClient()
          >>> resource = client.subscription_path('[PROJECT]', '[SUBSCRIPTION]')
          >>> permissions = []
          >>> response = client.test_iam_permissions(resource, permissions)

        Args:
          resource (string): REQUIRED: The resource for which the policy detail is being requested.
            ``resource`` is usually specified as a path. For example, a Project
            resource is specified as ``projects/{project}``.
          permissions (list[string]): The set of permissions to check for the ``resource``. Permissions with
            wildcards (such as '*' or 'storage.*') are not allowed. For more
            information see
            `IAM Overview <https://cloud.google.com/iam/docs/overview#permissions>`_.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = iam_policy_pb2.TestIamPermissionsRequest(
            resource=resource, permissions=permissions)
        return self._test_iam_permissions(request, options)
Exemple #28
0
class PublisherClient(object):
    """
    The service that an application uses to manipulate topics, and to send
    messages to a topic.
    """

    SERVICE_ADDRESS = 'pubsub.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _PAGE_DESCRIPTORS = {
        'list_topics': _PageDesc('page_token', 'next_page_token', 'topics'),
        'list_topic_subscriptions': _PageDesc('page_token', 'next_page_token',
                                              'subscriptions')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = (
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/pubsub', )

    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')
    _TOPIC_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/topics/{topic}')

    @classmethod
    def project_path(cls, project):
        """Returns a fully-qualified project resource name string."""
        return cls._PROJECT_PATH_TEMPLATE.render({'project': project, })

    @classmethod
    def topic_path(cls, project, topic):
        """Returns a fully-qualified topic resource name string."""
        return cls._TOPIC_PATH_TEMPLATE.render({
            'project': project,
            'topic': topic,
        })

    @classmethod
    def match_project_from_project_name(cls, project_name):
        """Parses the project from a project resource.

        Args:
          project_name (string): A fully-qualified path representing a project
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')

    @classmethod
    def match_project_from_topic_name(cls, topic_name):
        """Parses the project from a topic resource.

        Args:
          topic_name (string): A fully-qualified path representing a topic
            resource.

        Returns:
          A string representing the project.
        """
        return cls._TOPIC_PATH_TEMPLATE.match(topic_name).get('project')

    @classmethod
    def match_topic_from_topic_name(cls, topic_name):
        """Parses the topic from a topic resource.

        Args:
          topic_name (string): A fully-qualified path representing a topic
            resource.

        Returns:
          A string representing the topic.
        """
        return cls._TOPIC_PATH_TEMPLATE.match(topic_name).get('topic')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 credentials=None,
                 ssl_credentials=None,
                 scopes=None,
                 client_config=None,
                 app_name=None,
                 app_version='',
                 lib_name=None,
                 lib_version='',
                 metrics_headers=()):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          credentials (object): The authorization credentials to attach to
            requests. These credentials identify this application to the
            service.
          ssl_credentials (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          scopes (list[string]): A list of OAuth2 scopes to attach to requests.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          app_name (string): The name of the application calling
            the service. Recommended for analytics purposes.
          app_version (string): The version of the application calling
            the service. Recommended for analytics purposes.
          lib_name (string): The API library software used for calling
            the service. (Unless you are writing an API client itself,
            leave this as default.)
          lib_version (string): The API library software version used
            for calling the service. (Unless you are writing an API client
            itself, leave this as default.)
          metrics_headers (dict): A dictionary of values for tracking
            client library metrics. Ultimately serializes to a string
            (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be
            considered private.

        Returns:
          A PublisherClient object.
        """
        # Unless the calling application specifically requested
        # OAuth scopes, request everything.
        if scopes is None:
            scopes = self._ALL_SCOPES

        # Initialize an empty client config, if none is set.
        if client_config is None:
            client_config = {}

        # Initialize metrics_headers as an ordered dictionary
        # (cuts down on cardinality of the resulting string slightly).
        metrics_headers = collections.OrderedDict(metrics_headers)
        metrics_headers['gl-python'] = platform.python_version()

        # The library may or may not be set, depending on what is
        # calling this client. Newer client libraries set the library name
        # and version.
        if lib_name:
            metrics_headers[lib_name] = lib_version

        # Finally, track the GAPIC package version.
        metrics_headers['gapic'] = pkg_resources.get_distribution(
            'gapic-google-cloud-pubsub-v1', ).version

        # Load the configuration defaults.
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'publisher_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.pubsub.v1.Publisher',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            metrics_headers=metrics_headers,
            page_descriptors=self._PAGE_DESCRIPTORS, )
        self.iam_policy_stub = config.create_stub(
            iam_policy_pb2.IAMPolicyStub,
            channel=channel,
            service_path=service_path,
            service_port=port,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)
        self.publisher_stub = config.create_stub(
            pubsub_pb2.PublisherStub,
            channel=channel,
            service_path=service_path,
            service_port=port,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)

        self._create_topic = api_callable.create_api_call(
            self.publisher_stub.CreateTopic, settings=defaults['create_topic'])
        self._publish = api_callable.create_api_call(
            self.publisher_stub.Publish, settings=defaults['publish'])
        self._get_topic = api_callable.create_api_call(
            self.publisher_stub.GetTopic, settings=defaults['get_topic'])
        self._list_topics = api_callable.create_api_call(
            self.publisher_stub.ListTopics, settings=defaults['list_topics'])
        self._list_topic_subscriptions = api_callable.create_api_call(
            self.publisher_stub.ListTopicSubscriptions,
            settings=defaults['list_topic_subscriptions'])
        self._delete_topic = api_callable.create_api_call(
            self.publisher_stub.DeleteTopic, settings=defaults['delete_topic'])
        self._set_iam_policy = api_callable.create_api_call(
            self.iam_policy_stub.SetIamPolicy,
            settings=defaults['set_iam_policy'])
        self._get_iam_policy = api_callable.create_api_call(
            self.iam_policy_stub.GetIamPolicy,
            settings=defaults['get_iam_policy'])
        self._test_iam_permissions = api_callable.create_api_call(
            self.iam_policy_stub.TestIamPermissions,
            settings=defaults['test_iam_permissions'])

    # Service calls
    def create_topic(self, name, options=None):
        """
        Creates the given topic with the given name.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import publisher_client
          >>> api = publisher_client.PublisherClient()
          >>> name = api.topic_path('[PROJECT]', '[TOPIC]')
          >>> response = api.create_topic(name)

        Args:
          name (string): The name of the topic. It must have the format
            ``\"projects/{project}/topics/{topic}\"``. ``{topic}`` must start with a letter,
            and contain only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes (``-``),
            underscores (``_``), periods (``.``), tildes (``~``), plus (``+``) or percent
            signs (``%``). It must be between 3 and 255 characters in length, and it
            must not start with ``\"goog\"``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Topic` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = pubsub_pb2.Topic(name=name)
        return self._create_topic(request, options)

    def publish(self, topic, messages, options=None):
        """
        Adds one or more messages to the topic. Returns ``NOT_FOUND`` if the topic
        does not exist. The message payload must not be empty; it must contain
        either a non-empty data field, or at least one attribute.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import publisher_client
          >>> from google.cloud.proto.pubsub.v1 import pubsub_pb2
          >>> api = publisher_client.PublisherClient()
          >>> topic = api.topic_path('[PROJECT]', '[TOPIC]')
          >>> data = b''
          >>> messages_element = pubsub_pb2.PubsubMessage(data)
          >>> messages = [messages_element]
          >>> response = api.publish(topic, messages)

        Args:
          topic (string): The messages in the request will be published on this topic.
            Format is ``projects/{project}/topics/{topic}``.
          messages (list[:class:`google.cloud.proto.pubsub.v1.pubsub_pb2.PubsubMessage`]): The messages to publish.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.PublishResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = pubsub_pb2.PublishRequest(topic=topic, messages=messages)
        return self._publish(request, options)

    def get_topic(self, topic, options=None):
        """
        Gets the configuration of a topic.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import publisher_client
          >>> api = publisher_client.PublisherClient()
          >>> topic = api.topic_path('[PROJECT]', '[TOPIC]')
          >>> response = api.get_topic(topic)

        Args:
          topic (string): The name of the topic to get.
            Format is ``projects/{project}/topics/{topic}``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Topic` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = pubsub_pb2.GetTopicRequest(topic=topic)
        return self._get_topic(request, options)

    def list_topics(self, project, page_size=0, options=None):
        """
        Lists matching topics.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import publisher_client
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = publisher_client.PublisherClient()
          >>> project = api.project_path('[PROJECT]')
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_topics(project):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_topics(project, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          project (string): The name of the cloud project that topics belong to.
            Format is ``projects/{project}``.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.cloud.proto.pubsub.v1.pubsub_pb2.Topic` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = pubsub_pb2.ListTopicsRequest(
            project=project, page_size=page_size)
        return self._list_topics(request, options)

    def list_topic_subscriptions(self, topic, page_size=0, options=None):
        """
        Lists the name of the subscriptions for this topic.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import publisher_client
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = publisher_client.PublisherClient()
          >>> topic = api.topic_path('[PROJECT]', '[TOPIC]')
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_topic_subscriptions(topic):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_topic_subscriptions(topic, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          topic (string): The name of the topic that subscriptions are attached to.
            Format is ``projects/{project}/topics/{topic}``.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of string instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = pubsub_pb2.ListTopicSubscriptionsRequest(
            topic=topic, page_size=page_size)
        return self._list_topic_subscriptions(request, options)

    def delete_topic(self, topic, options=None):
        """
        Deletes the topic with the given name. Returns ``NOT_FOUND`` if the topic
        does not exist. After a topic is deleted, a new topic may be created with
        the same name; this is an entirely new topic with none of the old
        configuration or subscriptions. Existing subscriptions to this topic are
        not deleted, but their ``topic`` field is set to ``_deleted-topic_``.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import publisher_client
          >>> api = publisher_client.PublisherClient()
          >>> topic = api.topic_path('[PROJECT]', '[TOPIC]')
          >>> api.delete_topic(topic)

        Args:
          topic (string): Name of the topic to delete.
            Format is ``projects/{project}/topics/{topic}``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = pubsub_pb2.DeleteTopicRequest(topic=topic)
        self._delete_topic(request, options)

    def set_iam_policy(self, resource, policy, options=None):
        """
        Sets the access control policy on the specified resource. Replaces any
        existing policy.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import publisher_client
          >>> from google.iam.v1 import policy_pb2
          >>> api = publisher_client.PublisherClient()
          >>> resource = api.topic_path('[PROJECT]', '[TOPIC]')
          >>> policy = policy_pb2.Policy()
          >>> response = api.set_iam_policy(resource, policy)

        Args:
          resource (string): REQUIRED: The resource for which the policy is being specified.
            ``resource`` is usually specified as a path. For example, a Project
            resource is specified as ``projects/{project}``.
          policy (:class:`google.iam.v1.policy_pb2.Policy`): REQUIRED: The complete policy to be applied to the ``resource``. The size of
            the policy is limited to a few 10s of KB. An empty policy is a
            valid policy but certain Cloud Platform services (such as Projects)
            might reject them.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.v1.policy_pb2.Policy` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = iam_policy_pb2.SetIamPolicyRequest(
            resource=resource, policy=policy)
        return self._set_iam_policy(request, options)

    def get_iam_policy(self, resource, options=None):
        """
        Gets the access control policy for a resource.
        Returns an empty policy if the resource exists and does not have a policy
        set.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import publisher_client
          >>> api = publisher_client.PublisherClient()
          >>> resource = api.topic_path('[PROJECT]', '[TOPIC]')
          >>> response = api.get_iam_policy(resource)

        Args:
          resource (string): REQUIRED: The resource for which the policy is being requested.
            ``resource`` is usually specified as a path. For example, a Project
            resource is specified as ``projects/{project}``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.v1.policy_pb2.Policy` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = iam_policy_pb2.GetIamPolicyRequest(resource=resource)
        return self._get_iam_policy(request, options)

    def test_iam_permissions(self, resource, permissions, options=None):
        """
        Returns permissions that a caller has on the specified resource.
        If the resource does not exist, this will return an empty set of
        permissions, not a NOT_FOUND error.

        Example:
          >>> from google.cloud.gapic.pubsub.v1 import publisher_client
          >>> api = publisher_client.PublisherClient()
          >>> resource = api.topic_path('[PROJECT]', '[TOPIC]')
          >>> permissions = []
          >>> response = api.test_iam_permissions(resource, permissions)

        Args:
          resource (string): REQUIRED: The resource for which the policy detail is being requested.
            ``resource`` is usually specified as a path. For example, a Project
            resource is specified as ``projects/{project}``.
          permissions (list[string]): The set of permissions to check for the ``resource``. Permissions with
            wildcards (such as '*' or 'storage.*') are not allowed. For more
            information see
            `IAM Overview <https://cloud.google.com/iam/docs/overview#permissions>`_.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        # Create the request object.
        request = iam_policy_pb2.TestIamPermissionsRequest(
            resource=resource, permissions=permissions)
        return self._test_iam_permissions(request, options)
Exemple #29
0
class MetricsServiceV2Client(object):
    """Service for configuring logs-based metrics."""

    SERVICE_ADDRESS = 'logging.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _CODE_GEN_NAME_VERSION = 'gapic/0.1.0'

    _GAX_VERSION = pkg_resources.get_distribution('google-gax').version

    _PAGE_DESCRIPTORS = {
        'list_log_metrics': _PageDesc('page_token', 'next_page_token',
                                      'metrics')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = (
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/cloud-platform.read-only',
        'https://www.googleapis.com/auth/logging.admin',
        'https://www.googleapis.com/auth/logging.read',
        'https://www.googleapis.com/auth/logging.write',
    )

    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')
    _METRIC_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/metrics/{metric}')

    @classmethod
    def project_path(cls, project):
        """Returns a fully-qualified project resource name string."""
        return cls._PROJECT_PATH_TEMPLATE.render({
            'project': project,
        })

    @classmethod
    def metric_path(cls, project, metric):
        """Returns a fully-qualified metric resource name string."""
        return cls._METRIC_PATH_TEMPLATE.render({
            'project': project,
            'metric': metric,
        })

    @classmethod
    def match_project_from_project_name(cls, project_name):
        """Parses the project from a project resource.

        Args:
          project_name (string): A fully-qualified path representing a project
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')

    @classmethod
    def match_project_from_metric_name(cls, metric_name):
        """Parses the project from a metric resource.

        Args:
          metric_name (string): A fully-qualified path representing a metric
            resource.

        Returns:
          A string representing the project.
        """
        return cls._METRIC_PATH_TEMPLATE.match(metric_name).get('project')

    @classmethod
    def match_metric_from_metric_name(cls, metric_name):
        """Parses the metric from a metric resource.

        Args:
          metric_name (string): A fully-qualified path representing a metric
            resource.

        Returns:
          A string representing the metric.
        """
        return cls._METRIC_PATH_TEMPLATE.match(metric_name).get('metric')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 credentials=None,
                 ssl_credentials=None,
                 scopes=None,
                 client_config=None,
                 app_name='gax',
                 app_version=_GAX_VERSION):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          credentials (object): The authorization credentials to attach to
            requests. These credentials identify this application to the
            service.
          ssl_credentials (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          scopes (list[string]): A list of OAuth2 scopes to attach to requests.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          app_name (string): The codename of the calling service.
          app_version (string): The version of the calling service.

        Returns:
          A MetricsServiceV2Client object.
        """
        if scopes is None:
            scopes = self._ALL_SCOPES
        if client_config is None:
            client_config = {}
        goog_api_client = '{}/{} {} gax/{} python/{}'.format(
            app_name, app_version, self._CODE_GEN_NAME_VERSION,
            self._GAX_VERSION, platform.python_version())
        metadata = [('x-goog-api-client', goog_api_client)]
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'metrics_service_v2_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.logging.v2.MetricsServiceV2',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            kwargs={'metadata': metadata},
            page_descriptors=self._PAGE_DESCRIPTORS)
        self.metrics_service_v2_stub = config.create_stub(
            logging_metrics_pb2.MetricsServiceV2Stub,
            channel=channel,
            service_path=service_path,
            service_port=port,
            credentials=credentials,
            scopes=scopes,
            ssl_credentials=ssl_credentials)

        self._list_log_metrics = api_callable.create_api_call(
            self.metrics_service_v2_stub.ListLogMetrics,
            settings=defaults['list_log_metrics'])
        self._get_log_metric = api_callable.create_api_call(
            self.metrics_service_v2_stub.GetLogMetric,
            settings=defaults['get_log_metric'])
        self._create_log_metric = api_callable.create_api_call(
            self.metrics_service_v2_stub.CreateLogMetric,
            settings=defaults['create_log_metric'])
        self._update_log_metric = api_callable.create_api_call(
            self.metrics_service_v2_stub.UpdateLogMetric,
            settings=defaults['update_log_metric'])
        self._delete_log_metric = api_callable.create_api_call(
            self.metrics_service_v2_stub.DeleteLogMetric,
            settings=defaults['delete_log_metric'])

    # Service calls
    def list_log_metrics(self, parent, page_size=0, options=None):
        """
        Lists logs-based metrics.

        Example:
          >>> from google.cloud.gapic.logging.v2 import metrics_service_v2_client
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = metrics_service_v2_client.MetricsServiceV2Client()
          >>> parent = api.project_path('[PROJECT]')
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_log_metrics(parent):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_log_metrics(parent, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          parent (string): Required. The name of the project containing the metrics:

            ::

                \"projects/[PROJECT_ID]\"
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.cloud.grpc.logging.v2.logging_metrics_pb2.LogMetric` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = logging_metrics_pb2.ListLogMetricsRequest(
            parent=parent, page_size=page_size)
        return self._list_log_metrics(request, options)

    def get_log_metric(self, metric_name, options=None):
        """
        Gets a logs-based metric.

        Example:
          >>> from google.cloud.gapic.logging.v2 import metrics_service_v2_client
          >>> api = metrics_service_v2_client.MetricsServiceV2Client()
          >>> metric_name = api.metric_path('[PROJECT]', '[METRIC]')
          >>> response = api.get_log_metric(metric_name)

        Args:
          metric_name (string): The resource name of the desired metric:

            ::

                \"projects/[PROJECT_ID]/metrics/[METRIC_ID]\"
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.grpc.logging.v2.logging_metrics_pb2.LogMetric` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = logging_metrics_pb2.GetLogMetricRequest(
            metric_name=metric_name)
        return self._get_log_metric(request, options)

    def create_log_metric(self, parent, metric, options=None):
        """
        Creates a logs-based metric.

        Example:
          >>> from google.cloud.gapic.logging.v2 import metrics_service_v2_client
          >>> from google.cloud.grpc.logging.v2 import logging_metrics_pb2
          >>> api = metrics_service_v2_client.MetricsServiceV2Client()
          >>> parent = api.project_path('[PROJECT]')
          >>> metric = logging_metrics_pb2.LogMetric()
          >>> response = api.create_log_metric(parent, metric)

        Args:
          parent (string): The resource name of the project in which to create the metric:

            ::

                \"projects/[PROJECT_ID]\"

            The new metric must be provided in the request.
          metric (:class:`google.cloud.grpc.logging.v2.logging_metrics_pb2.LogMetric`): The new logs-based metric, which must not have an identifier that
            already exists.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.grpc.logging.v2.logging_metrics_pb2.LogMetric` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = logging_metrics_pb2.CreateLogMetricRequest(parent=parent,
                                                             metric=metric)
        return self._create_log_metric(request, options)

    def update_log_metric(self, metric_name, metric, options=None):
        """
        Creates or updates a logs-based metric.

        Example:
          >>> from google.cloud.gapic.logging.v2 import metrics_service_v2_client
          >>> from google.cloud.grpc.logging.v2 import logging_metrics_pb2
          >>> api = metrics_service_v2_client.MetricsServiceV2Client()
          >>> metric_name = api.metric_path('[PROJECT]', '[METRIC]')
          >>> metric = logging_metrics_pb2.LogMetric()
          >>> response = api.update_log_metric(metric_name, metric)

        Args:
          metric_name (string): The resource name of the metric to update:

            ::

                \"projects/[PROJECT_ID]/metrics/[METRIC_ID]\"

            The updated metric must be provided in the request and it's
            ``name`` field must be the same as ``[METRIC_ID]`` If the metric
            does not exist in ``[PROJECT_ID]``, then a new metric is created.
          metric (:class:`google.cloud.grpc.logging.v2.logging_metrics_pb2.LogMetric`): The updated metric.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.cloud.grpc.logging.v2.logging_metrics_pb2.LogMetric` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = logging_metrics_pb2.UpdateLogMetricRequest(
            metric_name=metric_name, metric=metric)
        return self._update_log_metric(request, options)

    def delete_log_metric(self, metric_name, options=None):
        """
        Deletes a logs-based metric.

        Example:
          >>> from google.cloud.gapic.logging.v2 import metrics_service_v2_client
          >>> api = metrics_service_v2_client.MetricsServiceV2Client()
          >>> metric_name = api.metric_path('[PROJECT]', '[METRIC]')
          >>> api.delete_log_metric(metric_name)

        Args:
          metric_name (string): The resource name of the metric to delete:

            ::

                \"projects/[PROJECT_ID]/metrics/[METRIC_ID]\"
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = logging_metrics_pb2.DeleteLogMetricRequest(
            metric_name=metric_name)
        self._delete_log_metric(request, options)
class GroupServiceApi(object):
    """
    The Group API lets you inspect and manage your
    `groups <https://cloud.google.comgoogle.monitoring.v3.Group>`_.

    A group is a named filter that is used to identify
    a collection of monitored resources. Groups are typically used to
    mirror the physical and/or logical topology of the environment.
    Because group membership is computed dynamically, monitored
    resources that are started in the future are automatically placed
    in matching groups. By using a group to name monitored resources in,
    for example, an alert policy, the target of that alert policy is
    updated automatically as monitored resources are added and removed
    from the infrastructure.
    """

    SERVICE_ADDRESS = 'monitoring.googleapis.com'
    """The default address of the service."""

    DEFAULT_SERVICE_PORT = 443
    """The default port of the service."""

    _CODE_GEN_NAME_VERSION = 'gapic/0.1.0'

    _GAX_VERSION = pkg_resources.get_distribution('google-gax').version

    _PAGE_DESCRIPTORS = {
        'list_groups': _PageDesc('page_token', 'next_page_token', 'group'),
        'list_group_members': _PageDesc('page_token', 'next_page_token',
                                        'members')
    }

    # The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _ALL_SCOPES = ()

    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')
    _GROUP_PATH_TEMPLATE = path_template.PathTemplate(
        'projects/{project}/groups/{group}')

    @classmethod
    def project_path(cls, project):
        """Returns a fully-qualified project resource name string."""
        return cls._PROJECT_PATH_TEMPLATE.render({
            'project': project,
        })

    @classmethod
    def group_path(cls, project, group):
        """Returns a fully-qualified group resource name string."""
        return cls._GROUP_PATH_TEMPLATE.render({
            'project': project,
            'group': group,
        })

    @classmethod
    def match_project_from_project_name(cls, project_name):
        """Parses the project from a project resource.

        Args:
          project_name (string): A fully-qualified path representing a project
            resource.

        Returns:
          A string representing the project.
        """
        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')

    @classmethod
    def match_project_from_group_name(cls, group_name):
        """Parses the project from a group resource.

        Args:
          group_name (string): A fully-qualified path representing a group
            resource.

        Returns:
          A string representing the project.
        """
        return cls._GROUP_PATH_TEMPLATE.match(group_name).get('project')

    @classmethod
    def match_group_from_group_name(cls, group_name):
        """Parses the group from a group resource.

        Args:
          group_name (string): A fully-qualified path representing a group
            resource.

        Returns:
          A string representing the group.
        """
        return cls._GROUP_PATH_TEMPLATE.match(group_name).get('group')

    def __init__(self,
                 service_path=SERVICE_ADDRESS,
                 port=DEFAULT_SERVICE_PORT,
                 channel=None,
                 metadata_transformer=None,
                 ssl_creds=None,
                 scopes=None,
                 client_config=None,
                 app_name='gax',
                 app_version=_GAX_VERSION):
        """Constructor.

        Args:
          service_path (string): The domain name of the API remote host.
          port (int): The port on which to connect to the remote host.
          channel (:class:`grpc.Channel`): A ``Channel`` instance through
            which to make calls.
          ssl_creds (:class:`grpc.ChannelCredentials`): A
            ``ChannelCredentials`` instance for use with an SSL-enabled
            channel.
          client_config (dict):
            A dictionary for call options for each method. See
            :func:`google.gax.construct_settings` for the structure of
            this data. Falls back to the default config if not specified
            or the specified config is missing data points.
          metadata_transformer (Callable[[], list]): A function that creates
             the metadata for requests.
          app_name (string): The codename of the calling service.
          app_version (string): The version of the calling service.

        Returns:
          A GroupServiceApi object.
        """
        if scopes is None:
            scopes = self._ALL_SCOPES
        if client_config is None:
            client_config = {}
        goog_api_client = '{}/{} {} gax/{} python/{}'.format(
            app_name, app_version, self._CODE_GEN_NAME_VERSION,
            self._GAX_VERSION, platform.python_version())
        metadata = [('x-goog-api-client', goog_api_client)]
        default_client_config = json.loads(
            pkg_resources.resource_string(
                __name__, 'group_service_client_config.json').decode())
        defaults = api_callable.construct_settings(
            'google.monitoring.v3.GroupService',
            default_client_config,
            client_config,
            config.STATUS_CODE_NAMES,
            kwargs={'metadata': metadata},
            page_descriptors=self._PAGE_DESCRIPTORS)
        self.group_service_stub = config.create_stub(
            group_service_pb2.GroupServiceStub,
            service_path,
            port,
            ssl_creds=ssl_creds,
            channel=channel,
            metadata_transformer=metadata_transformer,
            scopes=scopes)

        self._list_groups = api_callable.create_api_call(
            self.group_service_stub.ListGroups,
            settings=defaults['list_groups'])
        self._get_group = api_callable.create_api_call(
            self.group_service_stub.GetGroup, settings=defaults['get_group'])
        self._create_group = api_callable.create_api_call(
            self.group_service_stub.CreateGroup,
            settings=defaults['create_group'])
        self._update_group = api_callable.create_api_call(
            self.group_service_stub.UpdateGroup,
            settings=defaults['update_group'])
        self._delete_group = api_callable.create_api_call(
            self.group_service_stub.DeleteGroup,
            settings=defaults['delete_group'])
        self._list_group_members = api_callable.create_api_call(
            self.group_service_stub.ListGroupMembers,
            settings=defaults['list_group_members'])

    # Service calls
    def list_groups(self,
                    name,
                    children_of_group='',
                    ancestors_of_group='',
                    descendants_of_group='',
                    page_size=0,
                    options=None):
        """
        Lists the existing groups.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import group_service_api
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = group_service_api.GroupServiceApi()
          >>> name = api.project_path('[PROJECT]')
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_groups(name):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_groups(name, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          name (string): The project whose groups are to be listed. The format is
            ``\"projects/{project_id_or_number}\"``.
          children_of_group (string): A group name: ``\"projects/{project_id_or_number}/groups/{group_id}\"``.
            Returns groups whose ``parentName`` field contains the group
            name.  If no groups have this parent, the results are empty.
          ancestors_of_group (string): A group name: ``\"projects/{project_id_or_number}/groups/{group_id}\"``.
            Returns groups that are ancestors of the specified group.
            The groups are returned in order, starting with the immediate parent and
            ending with the most distant ancestor.  If the specified group has no
            immediate parent, the results are empty.
          descendants_of_group (string): A group name: ``\"projects/{project_id_or_number}/groups/{group_id}\"``.
            Returns the descendants of the specified group.  This is a superset of
            the results returned by the ``childrenOfGroup`` filter, and includes
            children-of-children, and so forth.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.monitoring.v3.group_pb2.Group` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = group_service_pb2.ListGroupsRequest(
            name=name,
            children_of_group=children_of_group,
            ancestors_of_group=ancestors_of_group,
            descendants_of_group=descendants_of_group,
            page_size=page_size)
        return self._list_groups(request, options)

    def get_group(self, name, options=None):
        """
        Gets a single group.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import group_service_api
          >>> api = group_service_api.GroupServiceApi()
          >>> name = api.group_path('[PROJECT]', '[GROUP]')
          >>> response = api.get_group(name)

        Args:
          name (string): The group to retrieve. The format is
            ``\"projects/{project_id_or_number}/groups/{group_id}\"``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.monitoring.v3.group_pb2.Group` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = group_service_pb2.GetGroupRequest(name=name)
        return self._get_group(request, options)

    def create_group(self, name, group, validate_only=False, options=None):
        """
        Creates a new group.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import group_service_api
          >>> from google.monitoring.v3 import group_pb2
          >>> api = group_service_api.GroupServiceApi()
          >>> name = api.project_path('[PROJECT]')
          >>> group = group_pb2.Group()
          >>> response = api.create_group(name, group)

        Args:
          name (string): The project in which to create the group. The format is
            ``\"projects/{project_id_or_number}\"``.
          group (:class:`google.monitoring.v3.group_pb2.Group`): A group definition. It is an error to define the ``name`` field because
            the system assigns the name.
          validate_only (bool): If true, validate this request but do not create the group.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.monitoring.v3.group_pb2.Group` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = group_service_pb2.CreateGroupRequest(
            name=name, group=group, validate_only=validate_only)
        return self._create_group(request, options)

    def update_group(self, group, validate_only=False, options=None):
        """
        Updates an existing group.
        You can change any group attributes except ``name``.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import group_service_api
          >>> from google.monitoring.v3 import group_pb2
          >>> api = group_service_api.GroupServiceApi()
          >>> group = group_pb2.Group()
          >>> response = api.update_group(group)

        Args:
          group (:class:`google.monitoring.v3.group_pb2.Group`): The new definition of the group.  All fields of the existing group,
            excepting ``name``, are replaced with the corresponding fields of this group.
          validate_only (bool): If true, validate this request but do not update the existing group.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.monitoring.v3.group_pb2.Group` instance.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = group_service_pb2.UpdateGroupRequest(
            group=group, validate_only=validate_only)
        return self._update_group(request, options)

    def delete_group(self, name, options=None):
        """
        Deletes an existing group.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import group_service_api
          >>> api = group_service_api.GroupServiceApi()
          >>> name = api.group_path('[PROJECT]', '[GROUP]')
          >>> api.delete_group(name)

        Args:
          name (string): The group to delete. The format is
            ``\"projects/{project_id_or_number}/groups/{group_id}\"``.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        request = group_service_pb2.DeleteGroupRequest(name=name)
        self._delete_group(request, options)

    def list_group_members(self,
                           name,
                           page_size=0,
                           filter_='',
                           interval=None,
                           options=None):
        """
        Lists the monitored resources that are members of a group.

        Example:
          >>> from google.cloud.gapic.monitoring.v3 import group_service_api
          >>> from google.gax import CallOptions, INITIAL_PAGE
          >>> api = group_service_api.GroupServiceApi()
          >>> name = api.group_path('[PROJECT]', '[GROUP]')
          >>>
          >>> # Iterate over all results
          >>> for element in api.list_group_members(name):
          >>>   # process element
          >>>   pass
          >>>
          >>> # Or iterate over results one page at a time
          >>> for page in api.list_group_members(name, options=CallOptions(page_token=INITIAL_PAGE)):
          >>>   for element in page:
          >>>     # process element
          >>>     pass

        Args:
          name (string): The group whose members are listed. The format is
            ``\"projects/{project_id_or_number}/groups/{group_id}\"``.
          page_size (int): The maximum number of resources contained in the
            underlying API response. If page streaming is performed per-
            resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number
            of resources in a page.
          filter_ (string): An optional `list filter <https://cloud.google.com/monitoring/api/learn_more#filtering>`_ describing
            the members to be returned.  The filter may reference the type, labels, and
            metadata of monitored resources that comprise the group.
            For example, to return only resources representing Compute Engine VM
            instances, use this filter:

                resource.type = \"gce_instance\"
          interval (:class:`google.monitoring.v3.common_pb2.TimeInterval`): An optional time interval for which results should be returned. Only
            members that were part of the group during the specified interval are
            included in the response.  If no interval is provided then the group
            membership over the last minute is returned.
          options (:class:`google.gax.CallOptions`): Overrides the default
            settings for this call, e.g, timeout, retries etc.

        Returns:
          A :class:`google.gax.PageIterator` instance. By default, this
          is an iterable of :class:`google.api.monitored_resource_pb2.MonitoredResource` instances.
          This object can also be configured to iterate over the pages
          of the response through the `CallOptions` parameter.

        Raises:
          :exc:`google.gax.errors.GaxError` if the RPC is aborted.
          :exc:`ValueError` if the parameters are invalid.
        """
        if interval is None:
            interval = common_pb2.TimeInterval()
        request = group_service_pb2.ListGroupMembersRequest(
            name=name, page_size=page_size, filter=filter_, interval=interval)
        return self._list_group_members(request, options)