
     &                         d Z ddlmZ ddlmZ ddlm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ZdZdZ G d de      Zd Zy)z@Utility methods to aid in interacting with a GCS results bucket.    )absolute_import)division)unicode_literalsN)
exceptions)transfer)util)apis)log)	resourceszgs://i  i  c                   0    e Zd ZdZd Zd Zd ZddZd Zy)	ResultsBucketOpsz@A utility class to encapsulate operations on the results bucket.c                    || _         || _        t        j                  dd      | _        || _        |r| j                  |       n| j                  ||      }t        j                  j                  |d      }|j                  | _        dj                  || j
                        | _        dj                  || j
                        | _        t!        j"                  dj                  | j                               y	)
a  Construct a ResultsBucketOps object to be used with a single matrix run.

    Args:
      project: string containing the Google Cloud Platform project id.
      bucket_name: string with the user-supplied name of a GCS bucket, or None.
      unique_obj_name: a unique-per-matrix GCS object name which will prefix all
        raw test result files within the supplied bucket_name.
      tr_client: ToolResults API client library generated by Apitools.
      tr_messages: ToolResults API messages library generated by Apitools.
      storage_client: Cloud Storage API client library generated by Apitools.

    Attributes:
      gcs_results_root: string containing the root path for the test results in
        'gs://{bucket}/{timestamp-suffix}' format.
    storagev1zstorage.buckets)
collectionz>https://console.developers.google.com/storage/browser/{b}/{t}/)btzgs://{b}/{t}/zRaw results root path is: [{0}]N)_project_storage_client	core_apisGetMessagesModule_storage_messages_gcs_object_nameEnsureBucketExists_GetDefaultBucketr   REGISTRYParsebucket_results_bucketformat_gcs_results_urlgcs_results_rootr
   info)selfprojectbucket_nameunique_obj_name	tr_clienttr_messagesstorage_client
bucket_refs           :lib/googlecloudsdk/api_lib/firebase/test/results_bucket.py__init__zResultsBucketOps.__init__*   s    " DM)D&88DID+D 
k***9kBk##)) 1 * 3J%,,D 	I	+!6!6	7 	 -$f{d6K6KfL 	HH.55d6K6KLM    c                    |j                  | j                        }	 |j                  j                  |      }|j                  S # t
        j                  $ rk}t        j                  |      \  }}|t        k(  rdj                  ||| j                        }ndj                  ||      }t        j                  |      d}~ww xY w)zEFetch the project's default GCS bucket name for storing tool results.)	projectIdztPermission denied while fetching the default results bucket (Error {0}: {1}). Is billing enabled for project: [{2}]?zSHttp error while trying to fetch the default results bucket:
ResponseError {0}: {1}N),ToolresultsProjectsInitializeSettingsRequestr   projectsInitializeSettingsdefaultBucketapitools_exceptions	HttpErrorr   GetErrorCodeAndMessageHTTP_FORBIDDENr    r   HttpException)	r$   r(   r)   requestresponseerrorcodeerr_msgmsgs	            r,   r   z"ResultsBucketOps._GetDefaultBucketR   s    FF-- G !G*##66w?h###(( 
*11%8mdG		JtWdmm4 	(tW% 	 $$S))
*s   &A CA&B>>Cc                 X   | j                   j                  |      }	 | j                  j                  j	                  |       y# t
        j                  $ rR}t        j                  |      \  }}|t        k7  r't        j                  dj                  |||            Y d}~nd}~ww xY wt        j                  j                  dj                  t         || j"                               | j                   j$                  }|j&                  j(                  }|j*                  j(                  }| j                   j%                  | j                   j-                  |      ||| j"                        }		 | j                  j                  j/                  |	       y# t
        j                  $ r}t        j                  |      \  }}|t0        k(  rd	j                  || j"                  
      }
n&dj                  |t        j2                  |            }
t        j                  |
      d}~ww xY w)a.  Create a GCS bucket if it doesn't already exist.

    Args:
      bucket_name: the name of the GCS bucket to create if it doesn't exist.

    Raises:
      BadFileException if the bucket name is malformed, the user does not
        have access rights to the bucket, or the bucket can't be created.
    )r   NzCould not access bucket [{b}]. Response error {c}: {e}. Please supply a valid bucket name or use the default bucket provided by Firebase Test Lab.)r   cez2Creating results bucket [{g}{b}] in project [{p}].)gr   p)name)r   predefinedAclpredefinedDefaultObjectAclr%   zUPermission denied while creating bucket [{b}]. Is billing enabled for project: [{p}]?)r   rD   z!Failed to create bucket [{b}] {e})r   rB   )r   StorageBucketsGetRequestr   bucketsGetr5   r6   r   r7   HTTP_NOT_FOUNDr   BadFileExceptionr    r
   statusPrint
GCS_PREFIXr   StorageBucketsInsertRequestPredefinedAclValueValuesEnumprojectPrivate)PredefinedDefaultObjectAclValueValuesEnumBucketInsertr8   GetError)r$   r&   get_reqerrr=   r>   
bucket_reqaclobjacl
insert_reqr?   s              r,   r   z#ResultsBucketOps.EnsureBucketExistse   s    $$== > G
7
""&&w/(( 711#6mdG		))- VkTWV5	7 	7 
 7 JJIfz[DMMfJL ''CCJ

1
1
@
@CAAPPF''CC%%,,+,>#)	 D J
-
""))*5(( 
-11#6mdG		86 	 3c(:; 	'',,
-s1   %A B)AB$$B)1%F H)*A:H$$H)Nc                    t         j                  j                  dj                  |             	 |j	                  t
              rt        |      \  }}| j                  j                  ||| j                  dj                  | j                  |xs t        j                  j                  |                  }| j                  j                  j!                  |       y	 t        j                  j#                  |      }| j                  j+                  |      }	 t,        j.                  j1                  ||      }	| j                  j7                  | j                  dj                  | j                  |xs t        j                  j                  |            |
      }
| j                  j                  j9                  |
|	      }|j:                  |k7  r:t'        j(                  dj                  |j:                  ||t=        |                  y# t        j$                  $ r% t'        j(                  dj                  |            w xY w# t2        j4                  $ r% t,        j.                  j1                  |d	      }	Y Gw xY w# t2        j>                  $ rI}t'        j(                  dj                  || j@                  tC        jD                  |                  d}~ww xY w)ax  Upload a file to the GCS results bucket using the storage API.

    Args:
      path: str, the absolute or relative path of the file to upload. File may
        be in located in GCS or the local filesystem.
      mimetype: str, the MIME type (aka Content-Type) that should be applied to
        files being copied from a non-GCS source to GCS. MIME types for GCS->GCS
        file uploads are not modified.
      destination_object: str, the destination object path in GCS to upload to,
        if it's different than the base name of the path argument.

    Raises:
      BadFileException if the file upload is not successful.
    z'Uploading [{f}] to Firebase Test Lab...)fz{obj}/{name})objrE   )sourceBucketsourceObjectdestinationBucketdestinationObjectz![{0}] not found or not accessible)size)	mime_typezapplication/octet-stream)r   rE   object)uploadzoCloud storage upload failure: Insert response.size={0} bytes but [{1}] contains {2} bytes.
Insert response: {3}z$Could not copy [{f}] to [{gcs}] {e}.)r^   gcsrB   N)#r
   rM   rN   r    
startswithrO   _SplitBucketAndObjectr   StorageObjectsCopyRequestr   r   ospathbasenamer   objectsCopygetsizer<   r   rL   Objectr   UploadFromFiler5   InvalidUserInputErrorStorageObjectsInsertRequestrU   rd   reprr6   r"   r   rV   )r$   rm   mimetypedestination_objectfile_bucketfile_objcopy_req	file_sizesrc_objrg   r\   r;   rX   s                r,   UploadFileToGcsz ResultsBucketOps.UploadFileToGcs   s    JJ>EEEMN*L		$ 5d ;X))CC$!"22,33))'E277+;+;H+E 4 G	 D H 	$$))(3	;ggood+) ((//Y/?	:??++DH+E&
 ++GG''&&))'A277+;+;D+A ' C  H 
 ''//66z>D 7 F==I%++DvhmmT9d8nEG G &% xx 	;++,O-3VD\; ;	; #88 	:??++8 , :&	:" (( L''
06Dd33t}}S7I6JL LLsV   B-J  H ?J !I =CJ 8I

J 4JJ JJ K$AKK$c                 t    t         j                  j                  dj                  | j                               y )Nz7Raw results will be stored in your GCS bucket at [{0}]
)r
   rM   rN   r    r!   )r$   s    r,   LogGcsResultsUrlz!ResultsBucketOps.LogGcsResultsUrl   s'    JJOfT2235r.   )NN)	__name__
__module____qualname____doc__r-   r   r   r   r    r.   r,   r   r   '   s#    H&NP*&2-h:Lx5r.   r   c                     | t        t              d j                  d      j                  dd      }t        |      dk7  r$t	        j
                  dj                  |             |S )zHSplit a GCS path into bucket & object tokens, or raise BadFileException.N/      z.[{0}] is not a valid Google Cloud Storage path)lenrO   stripsplitr   rL   r    )gcs_pathtokenss     r,   rj   rj      s_    C
O$%++C066sA>&[A

%
%8??IK K	-r.   )r   
__future__r   r   r   rl   apitools.base.pyr   r5   r   $googlecloudsdk.api_lib.firebase.testr   googlecloudsdk.api_lib.utilr	   r   googlecloudsdk.calliopegooglecloudsdk.corer
   r   rO   r8   rK   rf   r   rj   r   r.   r,   <module>r      sQ     G &  ' 	 > % 5 9 . # ) 
p5v p5fr.   