a
    !fH                     @   s   d Z ddlZddlmZ ddlmZ ddlmZ ddlm	Z
 ddlmZ ddlmZ dd	lmZ dd
lmZ dZedZedZdZed Zed Zee
jiZdd ZdddZdd ZG dd deZG dd deZ dS )z;User friendly container for Google Cloud Bigtable Instance.    N)operations_pb2)_pb_timestamp_to_datetime)instance_pb2)bigtable_instance_admin_pb2)bigtable_table_admin_pb2Cluster)DEFAULT_SERVE_NODESTablezsee-existing-clusterzH^projects/(?P<project>[^/]+)/instances/(?P<instance_id>[a-z][-a-z0-9]*)$z^operations/projects/([^/]+)/instances/([a-z][-a-z0-9]*)/locations/(?P<location_id>[a-z][-a-z0-9]*)/operations/(?P<operation_id>\d+)$z$type.googleapis.com/google.bigtable.z	admin.v2.CreateInstanceMetadatac                 C   sb   d| j j }tj|| jtj| jdd}|j| j }| j	d | j |_	|d | j
 |_| j|_|S )a   Creates a protobuf request for a CreateInstance request.

    :type instance: :class:`Instance`
    :param instance: The instance to be created.

    :rtype: :class:`.messages_v2_pb2.CreateInstanceRequest`
    :returns: The CreateInstance request object containing the instance info.
    z	projects/display_name)parentinstance_idinstancez
/clusters/z/locations/)_clientprojectmessages_v2_pb2ZCreateInstanceRequestr   data_v2_pb2Instancer   clustersname_cluster_location_idlocation_cluster_serve_nodesserve_nodes)r   parent_namemessagecluster r    Y/var/www/html/python-backend/venv/lib/python3.9/site-packages/gcloud/bigtable/instance.py_prepare_create_request1   s    	r"   c                 C   s:   |dur$|| j kr$td|| j f t| j  }|| jS )a  Convert a serialized "google.protobuf.Any" value to actual type.

    :type any_val: :class:`google.protobuf.any_pb2.Any`
    :param any_val: A serialized protobuf value container.

    :type expected_type: str
    :param expected_type: (Optional) The type URL we expect ``any_val``
                          to have.

    :rtype: object
    :returns: The de-serialized object.
    :raises: :class:`ValueError <exceptions.ValueError>` if the
             ``expected_type`` does not match the ``type_url`` on the input.
    NzExpected type: %s, Received: %s)Ztype_url
ValueError_TYPE_URL_MAPZ
FromStringvalue)Zany_valexpected_typeZcontainer_classr    r    r!   _parse_pb_any_to_nativeJ   s    
r'   c                 C   sV   t | j}|du r td| j|d}t|d}t| j}t|j	}|||fS )a  Processes a create protobuf response.

    :type operation_pb: :class:`google.longrunning.operations_pb2.Operation`
    :param operation_pb: The long-running operation response from a
                         Create/Update/Undelete instance request.

    :rtype: (int, str, datetime)
    :returns: (operation_id, location_id, operation_begin).
    :raises: :class:`ValueError <exceptions.ValueError>` if the operation name
             doesn't match the :data:`_OPERATION_NAME_RE` regex.
    NzFOperation name was not in the expected format after instance creation.location_idoperation_id)
_OPERATION_NAME_REmatchr   r#   groupintr'   metadatar   Zrequest_time)operation_pbr+   r(   r)   Zrequest_metadataZoperation_beginr    r    r!   _process_operation`   s    

r0   c                   @   s2   e Zd ZdZdddZdd Zdd Zd	d
 ZdS )	Operationa  Representation of a Google API Long-Running Operation.

    In particular, these will be the result of operations on
    instances using the Cloud Bigtable API.

    :type op_type: str
    :param op_type: The type of operation being performed. Expect
                    ``create``, ``update`` or ``undelete``.

    :type op_id: int
    :param op_id: The ID of the operation.

    :type begin: :class:`datetime.datetime`
    :param begin: The time when the operation was started.

    :type location_id: str
    :param location_id: ID of the location in which the operation is running

    :type instance: :class:`Instance`
    :param instance: The instance that created the operation.
    Nc                 C   s(   || _ || _|| _|| _|| _d| _d S NF)op_typeop_idbeginr(   	_instance	_complete)selfr3   r4   r5   r(   r   r    r    r!   __init__   s    zOperation.__init__c                 C   sX   t || jsdS |j| jkoV|j| jkoV|j| jkoV|j| jkoV|j| jkoV|j| jkS r2   )
isinstance	__class__r3   r4   r5   r(   r6   r7   r8   otherr    r    r!   __eq__   s    




zOperation.__eq__c                 C   s   |  | S Nr>   r<   r    r    r!   __ne__   s    zOperation.__ne__c                 C   s`   | j rtdd| jj| j| jf }tj|d}| jjj	
|| jjj}|jrXd| _ dS dS dS )a  Check if the operation has finished.

        :rtype: bool
        :returns: A boolean indicating if the current operation has completed.
        :raises: :class:`ValueError <exceptions.ValueError>` if the operation
                 has already completed.
        zThe operation has completed.z(operations/%s/locations/%s/operations/%dr   TFN)r7   r#   r6   r   r(   r4   r   ZGetOperationRequestr   Z_operations_stubZGetOperationtimeout_secondsdone)r8   Zoperation_name
request_pbr/   r    r    r!   finished   s    

zOperation.finished)N)__name__
__module____qualname____doc__r9   r>   rA   rF   r    r    r    r!   r1   {   s
   

r1   c                   @   s   e Zd ZdZedefddZdd Zedd Z	d	d
 Z
edd Zdd Zdd Zdd Zdd Zdd Zdd Zd"ddZdd Zdd Zd d! ZdS )#r   aI  Representation of a Google Cloud Bigtable Instance.

    We can use a :class:`Instance` to:

    * :meth:`reload` itself
    * :meth:`create` itself
    * :meth:`update` itself
    * :meth:`delete` itself
    * :meth:`undelete` itself

    .. note::

        For now, we leave out the ``default_storage_type`` (an enum)
        which if not sent will end up as :data:`.data_v2_pb2.STORAGE_SSD`.

    :type instance_id: str
    :param instance_id: The ID of the instance.

    :type client: :class:`Client <gcloud.bigtable.client.Client>`
    :param client: The client that owns the instance. Provides
                   authorization and a project ID.

    :type location_id: str
    :param location_id: ID of the location in which the instance will be
                        created.  Required for instances which do not yet
                        exist.

    :type display_name: str
    :param display_name: (Optional) The display name for the instance in the
                         Cloud Console UI. (Must be between 4 and 30
                         characters.) If this value is not set in the
                         constructor, will fall back to the instance ID.

    :type serve_nodes: int
    :param serve_nodes: (Optional) The number of nodes in the instance's
                        cluster; used to set up the instance's cluster.
    Nc                 C   s&   || _ |p|| _|| _|| _|| _d S r?   )r   r   r   r   r   )r8   r   clientr(   r   r   r    r    r!   r9      s
    
zInstance.__init__c                 C   s   |j std|j | _ dS )zpRefresh self from the server-provided protobuf.

        Helper for :meth:`from_pb` and :meth:`reload`.
        z/Instance protobuf does not contain display_nameN)r   r#   )r8   instance_pbr    r    r!   _update_from_pb   s    zInstance._update_from_pbc                 C   s\   t |j}|du r td|j|d|jkr8td|d}| ||t}|| |S )a  Creates a instance instance from a protobuf.

        :type instance_pb: :class:`instance_pb2.Instance`
        :param instance_pb: A instance protobuf object.

        :type client: :class:`Client <gcloud.bigtable.client.Client>`
        :param client: The client that owns the instance.

        :rtype: :class:`Instance`
        :returns: The instance parsed from the protobuf response.
        :raises: :class:`ValueError <exceptions.ValueError>` if the instance
                 name does not match
                 ``projects/{project}/instances/{instance_id}``
                 or if the parsed project ID does not match the project ID
                 on the client.
        Nz6Instance protobuf name was not in the expected format.r   zBProject ID on instance does not match the project ID on the clientr   )_INSTANCE_NAME_REr+   r   r#   r,   r   _EXISTING_INSTANCE_LOCATION_IDrM   )clsrL   rK   r+   r   resultr    r    r!   from_pb   s    

zInstance.from_pbc                 C   s"   | j  }| j| j|| j| jdS )zMake a copy of this instance.

        Copies the local data stored as simple types and copies the client
        attached to this instance.

        :rtype: :class:`.Instance`
        :returns: A copy of the current instance.
        r   )r   copyr;   r   r   r   )r8   Z
new_clientr    r    r!   rS     s
    	

zInstance.copyc                 C   s   | j jd | j S )aP  Instance name used in requests.

        .. note::
          This property will not change if ``instance_id`` does not,
          but the return value is not cached.

        The instance name is of the form

            ``"projects/{project}/instances/{instance_id}"``

        :rtype: str
        :returns: The instance name.
        z/instances/)r   project_namer   r8   r    r    r!   r   (  s    zInstance.namec                 C   s(   t || jsdS |j| jko&|j| jkS r2   )r:   r;   r   r   r<   r    r    r!   r>   9  s
    
zInstance.__eq__c                 C   s   |  | S r?   r@   r<   r    r    r!   rA   E  s    zInstance.__ne__c                 C   s0   t j| jd}| jj|| jj}| | dS )z&Reload the metadata for this instance.rB   N)r   ZGetInstanceRequestr   r   _instance_stubZGetInstancerC   rM   )r8   rE   rL   r    r    r!   reloadH  s
    zInstance.reloadc                 C   s<   t | }| jj|| jj}t|\}}}td|||| dS )aE  Create this instance.

        .. note::

            Uses the ``project`` and ``instance_id`` on the current
            :class:`Instance` in addition to the ``display_name``.
            To change them before creating, reset the values via

            .. code:: python

                instance.display_name = 'New display name'
                instance.instance_id = 'i-changed-my-mind'

            before calling :meth:`create`.

        :rtype: :class:`Operation`
        :returns: The long-running operation corresponding to the
                  create operation.
        create)r   )r"   r   rV   ZCreateInstancerC   r0   r1   )r8   rE   r/   r4   Zloc_idZop_beginr    r    r!   rX   S  s    zInstance.createc                 C   s*   t j| j| jd}| jj|| jj dS )a)  Update this instance.

        .. note::

            Updates the ``display_name``. To change that value before
            updating, reset its values via

            .. code:: python

                instance.display_name = 'New display name'

            before calling :meth:`update`.
        )r   r   N)r   r   r   r   r   rV   ZUpdateInstancerC   r8   rE   r    r    r!   updateo  s    zInstance.updatec                 C   s&   t j| jd}| jj|| jj dS )aW  Delete this instance.

        Marks a instance and all of its tables for permanent deletion
        in 7 days.

        Immediately upon completion of the request:

        * Billing will cease for all of the instance's reserved resources.
        * The instance's ``delete_time`` field will be set 7 days in
          the future.

        Soon afterward:

        * All tables within the instance will become unavailable.

        Prior to the instance's ``delete_time``:

        * The instance can be recovered with a call to ``UndeleteInstance``.
        * All other attempts to modify or delete the instance will be rejected.

        At the instance's ``delete_time``:

        * The instance and **all of its tables** will immediately and
          irrevocably disappear from the API, and their data will be
          permanently deleted.
        rB   N)r   ZDeleteInstanceRequestr   r   rV   ZDeleteInstancerC   rY   r    r    r!   delete  s    zInstance.delete   c                 C   s   t || |dS )a  Factory to create a cluster associated with this client.

        :type cluster_id: str
        :param cluster_id: The ID of the cluster.

        :type serve_nodes: int
        :param serve_nodes: (Optional) The number of nodes in the cluster.
                            Defaults to 3.

        :rtype: :class:`.Cluster`
        :returns: The cluster owned by this client.
        )r   r   )r8   Z
cluster_idr   r    r    r!   r     s    zInstance.clusterc                    sN   t j jd} jj| jj}dd |jD } fdd|jD }||fS )a  Lists clusters in this instance.

        :rtype: tuple
        :returns: A pair of results, the first is a list of :class:`.Cluster` s
                  returned and the second is a list of strings (the failed
                  locations in the request).
        r   c                 S   s   g | ]}|qS r    r    ).0r   r    r    r!   
<listcomp>  s   z*Instance.list_clusters.<locals>.<listcomp>c                    s   g | ]}t | qS r    )r   rR   )r^   Z
cluster_pbrU   r    r!   r_     s   )	r   ZListClustersRequestr   r   rV   ZListClustersrC   failed_locationsr   )r8   rE   Zlist_clusters_responser`   r   r    rU   r!   list_clusters  s    
zInstance.list_clustersc                 C   s
   t || S )zFactory to create a table associated with this instance.

        :type table_id: str
        :param table_id: The ID of the table.

        :rtype: :class:`Table <gcloud.bigtable.table.Table>`
        :returns: The table owned by this instance.
        r
   )r8   table_idr    r    r!   table  s    	zInstance.tablec                 C   s~   t j| jd}| jj|| jj}g }|jD ]L}| jd }|j|sVt	d|jf |jt
|d }|| | q,|S )aG  List the tables in this instance.

        :rtype: list of :class:`Table <gcloud.bigtable.table.Table>`
        :returns: The list of tables owned by the instance.
        :raises: :class:`ValueError <exceptions.ValueError>` if one of the
                 returned tables has a name that is not of the expected format.
        r]   z/tables/z$Table name %s not of expected formatN)table_messages_v2_pb2ZListTablesRequestr   r   Z_table_stubZ
ListTablesrC   Ztables
startswithr#   lenappendrc   )r8   rE   Ztable_list_pbrQ   Ztable_pbZtable_prefixrb   r    r    r!   list_tables  s    

zInstance.list_tables)r\   )rG   rH   rI   rJ   rO   r	   r9   rM   classmethodrR   rS   propertyr   r>   rA   rW   rX   rZ   r[   r   ra   rc   rh   r    r    r    r!   r      s*   '

	

 
r   )N)!rJ   reZgoogle.longrunningr   Zgcloud._helpersr   Zgcloud.bigtable._generatedr   r   r   r   r   rd   Zgcloud.bigtable.clusterr   r	   Zgcloud.bigtable.tabler   rO   compilerN   r*   Z_TYPE_URL_BASEZ_ADMIN_TYPE_URL_BASEZ_INSTANCE_CREATE_METADATAr   r$   r"   r'   r0   objectr1   r   r    r    r    r!   <module>   s,   


F