
     &                         S r SSKJr  SSKJr  SSKJr  SSKrSSKJr  SSKJ	r	  SSK
Jr  SS	KJr  SSKJr  SS
KJr  SSKJr  SrSrSr " S S\5      rS rg)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                   :    \ rS rSrSrS rS rS rS
S jrS r	S	r
g)ResultsBucketOps'   z@A utility class to encapsulate operations on the results bucket.c                    Xl         X`l        [        R                  " SS5      U l        X0l        U(       a  U R                  U5        OU R                  XE5      n[        R                  R                  USS9nUR                  U l        SR                  X R
                  S9U l        SR                  X R
                  S9U l        [         R"                  " SR                  U R                  5      5        g	)
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__ResultsBucketOps.__init__*   s    " M)&88DID+ 
k***9Bk##)) 1 * 3J%,,D 	I	+!6!6	7 	 -$f{6K6KfL 	HH.55d6K6KLM    c                    UR                  U R                  S9n UR                  R                  U5      nUR                  $ ! [
        R                   ak  n[        R                  " U5      u  pgU[        :X  a  SR                  XgU R                  5      nOSR                  Xg5      n[        R                  " U5      eSnAff = f)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   "ResultsBucketOps._GetDefaultBucketR   s    FF-- G !G*##66w?h###(( 
*11%8md		Jtdmm4 	(t% 	 $$S))
*s   &A CA&B<<Cc           	      6   U R                   R                  US9n U R                  R                  R	                  U5        g! [
        R                   aP  n[        R                  " U5      u  pEU[        :w  a$  [        R                  " SR                  XUS95      e SnAOSnAff = f[        R                  R                  SR                  [         XR"                  S95        U R                   R$                  nUR&                  R(                  nUR*                  R(                  nU R                   R%                  U R                   R-                  US9UUU R"                  S9n	 U R                  R                  R/                  U	5        g! [
        R                   a{  n[        R                  " U5      u  pEU[0        :X  a  S	R                  XR"                  S
9n
O$SR                  U[        R2                  " U5      S9n
[        R                  " U
5      eSnAff = f)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   rG   z!Failed to create bucket [{b}] {e})r   rE   )r   StorageBucketsGetRequestr   bucketsGetr7   r8   r   r9   HTTP_NOT_FOUNDr   BadFileExceptionr!   r
   statusPrint
GCS_PREFIXr   StorageBucketsInsertRequestPredefinedAclValueValuesEnumprojectPrivate)PredefinedDefaultObjectAclValueValuesEnumBucketInsertr:   GetError)r%   r'   get_reqerrr?   r@   
bucket_reqaclobjacl
insert_reqrA   s              r-   r   #ResultsBucketOps.EnsureBucketExistse   s    $$== > G
7
""&&w/(( 711#6md		))- VkWV5	7 	7 
 7 JJIfz[MMfJL ''CCJ

1
1
@
@CAAPPF''CC%%,,+,>#)	 D J
-
""))*5(( 
-11#6md		86 	 3c(:; 	'',,
-s1   %A B%AB  B%#%F	 	HA6HHNc                    [         R                  R                  SR                  US95         UR	                  [
        5      (       a  [        U5      u  pEU R                  R                  UUU R                  SR                  U R                  U=(       d    [        R                  R                  U5      S9S9nU R                  R                  R!                  U5        g [        R                  R#                  U5      nU R                  R+                  US9n [,        R.                  R1                  XS9n	U R                  R7                  U R                  SR                  U R                  U=(       d    [        R                  R                  U5      S9US
9n
U R                  R                  R9                  U
U	S9nUR:                  U:w  a:  [&        R(                  " SR                  UR:                  X[=        U5      5      5      eg! [        R$                   a&    [&        R(                  " SR                  U5      5      ef = f! [2        R4                   a"    [,        R.                  R1                  US	S9n	 GNDf = f! [2        R>                   aG  n[&        R(                  " SR                  XR@                  [B        RD                  " U5      S95      eSnAff = f)aL  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})objrH   )sourceBucketsourceObjectdestinationBucketdestinationObjectz![{0}] not found or not accessible)size)	mime_typezapplication/octet-stream)r   rH   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}.)rb   gcsrE   N)#r
   rP   rQ   r!   
startswithrR   _SplitBucketAndObjectr   StorageObjectsCopyRequestr    r   ospathbasenamer   objectsCopygetsizer>   r   rO   Objectr   UploadFromFiler7   InvalidUserInputErrorStorageObjectsInsertRequestrX   rh   reprr8   r#   r   rY   )r%   rq   mimetypedestination_objectfile_bucketfile_objcopy_req	file_sizesrc_objrk   r_   r=   r[   s                r-   UploadFileToGcs ResultsBucketOps.UploadFileToGcs   s    JJ>EEEMN*L		$	$ 5d ;))CC$!"22,33))'E277+;+;H+E 4 G	 D H 	$$))(3	;ggood+) ((//Y/?	:??++D+E&
 ++GG''&&))'A277+;+;D+A ' C  H 
 ''//66z>D 7 F==I%++DvhmmTd8nEG G &% xx 	;++,O-3VD\; ;	; #88 	:??++8 , :&	:" (( L''
06D33t}}S7I6JL LLsV   B0I>  H ?I> I 6CI> :II> 2I;7I> :I;;I> >KAKKc                 t    [         R                  R                  SR                  U R                  5      5        g )Nz7Raw results will be stored in your GCS bucket at [{0}]
)r
   rP   rQ   r!   r"   )r%   s    r-   LogGcsResultsUrl!ResultsBucketOps.LogGcsResultsUrl   s'    JJOfT2235r0   )r   r"   r   r    r   r   r#   )NN)__name__
__module____qualname____firstlineno____doc__r.   r   r   r   r   __static_attributes__ r0   r-   r   r   '   s#    H&NP*&2-h:Lx5r0   r   c                     U [        [        5      S R                  S5      R                  SS5      n[        U5      S:w  a%  [        R
                  " SR                  U 5      5      eU$ )zHSplit a GCS path into bucket & object tokens, or raise BadFileException.N/      z.[{0}] is not a valid Google Cloud Storage path)lenrR   stripsplitr   rO   r!   )gcs_pathtokenss     r-   rn   rn      s_    C
O$%++C066sA>&[A

%
%8??IK K	-r0   )r   
__future__r   r   r   rp   apitools.base.pyr   r7   r   $googlecloudsdk.api_lib.firebase.testr   googlecloudsdk.api_lib.utilr	   r   googlecloudsdk.calliopegooglecloudsdk.corer
   r   rR   r:   rN   rj   r   rn   r   r0   r-   <module>r      sQ     G &  ' 	 > % 5 9 . # ) 
p5v p5fr0   