
    `                     |   d Z ddlmZ ddlmZ ddlmZ ddlmZ ddlZddlZddlZddl	Z	ddl
Z
ddl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dZ G d de      Zd Z d Z!d Z"	 	 d&dZ#d Z$	 d'dZ%d Z&d Z'	 	 	 	 	 	 	 	 d(dZ(d Z)d Z*	 d'dZ+	 d'd Z,d! Z-d" Z.d# Z/d'd$Z0d% Z1y))z0Helper functions for tracker file functionality.    )absolute_import)print_function)division)unicode_literalsN)config)CommandException)GetGsutilStateDir)ResumableThreshold)UTF8)GetMd5)CreateDirIfNeededd   zCouldn't write tracker file (%s): %s. This can happen if gsutil is configured to save tracker files to an unwritable directory)encryption_key_sha256serialization_datac                   $    e Zd ZdZdZdZdZdZdZy)TrackerFileTypeuploaddownloaddownload_componentparallel_uploadsliced_downloadrewriteN)	__name__
__module____qualname__UPLOADDOWNLOADDOWNLOAD_COMPONENTPARALLEL_UPLOADSLICED_DOWNLOADREWRITE     %platform/gsutil/gslib/tracker_file.pyr   r   4   s!    &(+%/%/'r#   r   c                     t        | t        j                        r| j                  t              }| }n| }| j                  t              }t        j                  |      }d|j                         z   dz   |dd z   S )a"  Apply a hash function (SHA1) to shorten the passed file name.

  The spec for the hashed file name is as follows:

      TRACKER_<hash>_<trailing>

  where hash is a SHA1 hash on the original file name and trailing is
  the last 16 chars from the original file name. Max file name lengths
  vary by operating system so the goal of this function is to ensure
  the hashed version takes fewer than 100 characters.

  Args:
    filename: file name to be hashed. May be unicode or bytes.

  Returns:
    shorter, hashed version of passed file name
  TRACKER_.iN)	
isinstancesix	text_typeencoder   decodehashlibsha1	hexdigest)filenamefilename_bytesfilename_strms       r$   _HashFilenamer4   =   sh    $ #--(__T*NLN??4(Lll>"!	akkm	#c	)L,>	>>r#   c                      t        j                  ddt        j                  j	                  t               d            } t        |        | S )a  Looks up or creates the gsutil tracker file directory.

  This is the configured directory where gsutil keeps its resumable transfer
  tracker files. This function creates it if it doesn't already exist.

  Returns:
    The pathname to the tracker directory.
  GSUtilresumable_tracker_dirztracker-files)r   getospathjoinr	   r   )tracker_dirs    r$   CreateTrackerDirIfNeededr=   Y   s<     

8%<77<<(9(;_MO+K 	r#   c                     t        j                  ddd| d|d|d|d|d      }t        |t        j                        S )aU  Gets the tracker file name described by the arguments.

  Args:
    src_bucket_name: Source bucket (string).
    src_obj_name: Source object (string).
    dst_bucket_name: Destination bucket (string).
    dst_obj_name: Destination object (string)
    api_selector: API to use for this operation.

  Returns:
    File path to tracker file.
  [/\\]_	rewrite____z.token)resub_HashAndReturnPathr   r!   )src_bucket_namesrc_obj_namedst_bucket_namedst_obj_nameapi_selectorres_tracker_file_names         r$   GetRewriteTrackerFilePathrL   h   s?      66o|
 
1?3J3J	KKr#   c                    |t         j                  k(  r7t        j                  ddd| j                  d| j
                  d|d      }nt|t         j                  k(  rGt        j                  dddt        j                  j                  | j
                        d|d      }n|t         j                  k(  rEt        j                  dddt        j                  j                  | j
                        ||fz        }n|t         j                  k(  r9t        j                  ddd	| j                  d| j
                  d|d|d	      }nv|t         j                  k(  rFt        j                  ddd
t        j                  j                  | j
                        d|d      }n|t         j                  k(  r
t               t        |      S )a  Gets the tracker file name described by the arguments.

  Args:
    dst_url: Destination URL for tracker file.
    tracker_file_type: TrackerFileType for this operation.
    api_selector: API to use for this operation.
    src_url: Source URL for the source file name for parallel uploads.
    component_num: Component number if this is a download component, else None.

  Returns:
    File path to tracker file.
  r?   r@   resumable_upload__rB   z.urlresumable_download__z.etagz#resumable_download__%s__%s__%d.etagparallel_upload__sliced_download__)r   r   rC   rD   bucket_nameobject_namer   r9   r:   realpathr   r   r    r!   NotImplementedErrorrE   )dst_urltracker_file_typerJ   src_urlcomponent_numrK   s         r$   GetTrackerFilePathrZ      s   " /000VV3			g11<AB O444VV3			'--	.>? O>>>  VV3=			'--	.mLMN O;;;  VV3			g117LJK O;;;VV3			'--	.>? O333

	13D	EEr#   c                     t        t        | t        j                  |             t	        | |      }|D ]  }t        |        y)zDeletes all tracker files corresponding to an object download.

  Args:
    dst_url: StorageUrl describing the destination file.
    api_selector: The Cloud API implementation used.
  N)DeleteTrackerFilerZ   r   r   !GetSlicedDownloadTrackerFilePaths)rV   rJ   tracker_filestracker_files       r$   DeleteDownloadTrackerFilesr`      s?     /":":LIK 4G\J-#ll# $r#   c           	         t        | t        j                  |      }|g}|;d}	 t        |d      }t	        j
                  |      d   }	 |r|j                          	 t        |      D ].  }|j                  t        | t        j                  ||             0 |S # t        t        f$ r |cY |r|j                          S S w xY w# |r|j                          w w xY w)a  Gets a list of sliced download tracker file paths.

  The list consists of the parent tracker file path in index 0, and then
  any existing component tracker files in [1:].

  Args:
    dst_url: Destination URL for tracker file.
    api_selector: API to use for this operation.
    num_components: The number of component tracker files, if already known.
                    If not known, the number will be retrieved from the parent
                    tracker file on disk.
  Returns:
    File path to tracker file.
  Nrnum_componentsrY   )rZ   r   r    openjsonloadIOError
ValueErrorcloserangeappendr   )rV   rJ   rc   parallel_tracker_file_pathtracker_file_pathsr_   is          r$   r]   r]      s    "  2.. >23 L4c:lyy./?@n 
 a7*==')*	,- ! 
 Z   	 
  
 
s#   $B C+C  CC Cc                     t               }t        |       }t        |      j                         d|}|t        j
                  |}t        |      t        k  sJ |S )zHashes and returns a tracker file path.

  Args:
    res_tracker_file_name: The tracker file name prior to it being hashed.
    tracker_file_type: The TrackerFileType of res_tracker_file_name.

  Returns:
    Final (hashed) tracker file path.
  r@   )r=   r4   strlowerr9   seplenMAX_TRACKER_FILE_NAME_LENGTH)rK   rW   r7   hashed_tracker_file_nametracker_file_nametracker_file_paths         r$   rE   rE      se     34*+@A!$%6!7!=!=!?!9;"7"35		">	>>	>	r#   c                 t    | r6t         j                  j                  |       rt        j                  |        y y y N)r9   r:   existsunlink)rw   s    r$   r\   r\     s*    277>>*;<II  =r#   c                 L   | r@| j                   r4| j                  r(| j                  r|r|j                   r|j                  r|syt               }| |||||||
|||	fD ]8  }||j	                  t        j                  |      j                  d             : |j                         S )a`  Creates an MD5 hex digest of the parameters for a rewrite call.

  Resuming rewrites requires that the input parameters are identical. Thus,
  the rewrite tracker file needs to represent the input parameters. For
  easy comparison, hash the input values. If a user does a performs a
  same-source/same-destination rewrite via a different command (for example,
  with a changed ACL), the hashes will not match and we will restart the
  rewrite from the beginning.

  Args:
    src_obj_metadata: apitools Object describing source object. Must include
      bucket, name, and etag.
    dst_obj_metadata: apitools Object describing destination object. Must
      include bucket and object name
    projection: Projection used for the API call.
    src_generation: Optional source generation.
    gen_match: Optional generation precondition.
    meta_gen_match: Optional metageneration precondition.
    canned_acl: Optional canned ACL string.
    max_bytes_per_call: Optional maximum bytes rewritten per call.
    src_dec_key_sha256: Optional SHA256 hash string of decryption key for
        source object.
    dst_enc_key_sha256: Optional SHA256 hash string of encryption key for
        destination object.
    fields: Optional fields to include in response to call.

  Returns:
    MD5 hex digest Hash of the input parameters, or None if required parameters
    are missing.
  Nr   )	bucketnameetagr   updater)   r*   r+   r/   )src_obj_metadatadst_obj_metadata
projectionsrc_generation	gen_matchmeta_gen_match
canned_aclmax_bytes_per_callsrc_dec_key_sha256dst_enc_key_sha256fieldsmd5_hashinput_params                r$   HashRewriteParametersr     s    R "2"9"9


'7'<'<
"2"9"9


z
X(k oocmmK077?@!" 
			r#   c                    d}|sy	 t        | d      }|j                         j                  d      }||k(  r2|j                         j                  d      |r|j                          S S 	 |r|j                          yy# t        $ rW}|j
                  t
        j                  k7  r0t        j                  j                  d| d|j                  d       Y d}~od}~ww xY w# |r|j                          w w xY w)a~  Attempts to read a rewrite tracker file.

  Args:
    tracker_file_name: Tracker file path string.
    rewrite_params_hash: MD5 hex digest of rewrite call parameters constructed
        by HashRewriteParameters.

  Returns:
    String rewrite_token for resuming rewrite requests if a matching tracker
    file exists, None otherwise (which will result in starting a new rewrite).
  Nrb   
z!Couldn't read Copy tracker file (): z. Restarting copy from scratch.)re   readlinerstriprj   rh   errnoENOENTsysstderrwritestrerror)rw   rewrite_params_hashr_   existing_hashes        r$   ReadRewriteTrackerFiler   K  s     ,	
)3/L ))+2248M++""$++D1   ,   
 ?ww%,,	jj/=??  s1   AA> )C! >	CACC! CC! !C6c                 (    t        | |d|d       y)a  Writes a rewrite tracker file.

  Args:
    tracker_file_name: Tracker file path string.
    rewrite_params_hash: MD5 hex digest of rewrite call parameters constructed
        by HashRewriteParameters.
    rewrite_token: Rewrite token string returned by the service.
  r   N)_WriteTrackerFile)rw   r   rewrite_tokens      r$   WriteRewriteTrackerFiler   l  s     %"5}EGr#   c           	         | j                   sJ d}| j                  t               k  r||fS |j                  }|t        j
                  }	nt        j                  }	|d|z  z  }t        ||	||      }d}
	 t        |d      }
|	t        j
                  u rE|
j                         j                  d      }|| j                   k(  r||f|
r|
j                          S S |	t        j                  u rat        j                  |
j                               }|d   | j                   k(  r,|d   | j                  k(  r||d   f|
r|
j                          S S |j!                  d	|z         |
r|
j                          	 |	t        j
                  u rt/        |d| j                   z         ||fS |	t        j                  u rt1        || |       ||fS # t"        t$        f$ rX}t'        |t$              s|j(                  t(        j*                  k7  r!|j!                  d
|dt-        |      d       Y d}~d}~ww xY w# |
r|
j                          w w xY w)a?  Checks for a download tracker file and creates one if it does not exist.

  The methodology for determining the download start point differs between
  normal and sliced downloads. For normal downloads, the existing bytes in
  the file are presumed to be correct and have been previously downloaded from
  the server (if a tracker file exists). In this case, the existing file size
  is used to determine the download start point. For sliced downloads, the
  number of bytes previously retrieved from the server cannot be determined
  from the existing file size, and so the number of bytes known to have been
  previously downloaded is retrieved from the tracker file.

  Args:
    src_obj_metadata: Metadata for the source object. Must include etag and
                      generation.
    dst_url: Destination URL for tracker file.
    logger: For outputting log messages.
    api_selector: API to use for this operation.
    start_byte: The start byte of the byte range for this download.
    existing_file_size: Size of existing file for this download on disk.
    component_num: The component number, if this is a component of a parallel
                   download, else None.

  Returns:
    tracker_file_name: The name of the tracker file, if one was used.
    download_start_byte: The first byte that still needs to be downloaded.
  Nz component %drd   rb   r   r   
generationdownload_start_bytezPTracker file doesn't match for download of %s. Restarting download from scratch.z%Couldn't read download tracker file (r   z#. Restarting download from scratch.z%s
)r   sizer
   rS   r   r   r   rZ   re   r   r   rj   rf   loadsreadr   warnrh   ri   r(   r   r   rq   r   !WriteDownloadComponentTrackerFile)r   rV   loggerrJ   
start_byteexisting_file_sizerY   rw   download_namerW   r_   
etag_valuecomponent_datar   s                 r$   ReadOrCreateDownloadTrackerFiler   z  s]   B 
			/11 j((%%-'00'::_}44M():)57DF ,)3/LO444((*11$7j	',,	, "44"  ! 
o@@	@zz,"3"3"56n

 $4$9$9
9

&*:*E*E
E .1F"GG   KK )+89 :  /222'2B2G2G)GH 
J	&& O>>>%&79I&02	J	&&# :	 J !Z AGGu||$;kk.?QI J	J  s9   5AG AG G H+AH&!H. &H++H. .Ic                    | j                   sJ d}| j                  t               k  r|S |t        j                  }nt        j
                  }t        ||||      }d}	 t        |d      }|t        j                  u rC|j                         j                  d      }	|	| j                   k(  r||r|j                          S S |t        j
                  u r_t        j                  |j                               }
|
d   | j                   k(  r*|
d   | j                  k(  r|
d   |r|j                          S S |r|j                          |S # t        t         f$ r Y %w xY w# |r|j                          w w xY w)af  Returns the download starting point.

  The methodology of this function is the same as in
  ReadOrCreateDownloadTrackerFile, with the difference that we are not
  interested here in possibly creating a tracker file. In case there is no
  tracker file, this means the download starting point is start_byte.

  Args:
    src_obj_metadata: Metadata for the source object. Must include etag and
                      generation.
    dst_url: Destination URL for tracker file.
    api_selector: API to use for this operation.
    start_byte: The start byte of the byte range for this download.
    existing_file_size: Size of existing file for this download on disk.
    component_num: The component number, if this is a component of a parallel
                   download, else None.

  Returns:
    download_start_byte: The first byte that still needs to be downloaded.
  Nrd   rb   r   r   r   r   )r   r   r
   r   r   r   rZ   re   r   r   rj   rf   r   r   r   rh   ri   )r   rV   rJ   r   r   rY   rw   rW   r_   r   r   s              r$   GetDownloadStartByter     s   4 
			/11 '00'::():)57DF ,)3/LO444((*11$7j	',,	,!   
o@@	@zz,"3"3"56n

 $4$9$9
9

&*:*E*E
E34   
 :	 		
  s,   AE  AE EE EE E/c                 v    |j                   |j                  |d}t        | t        j                  |             y)zUpdates or creates a download component tracker file on disk.

  Args:
    tracker_file_name: The name of the tracker file.
    src_obj_metadata: Metadata for the source object. Must include etag.
    current_file_pos: The current position in the file.
  )r   r   r   N)r   r   r   rf   dumps)rw   r   current_file_posr   s       r$   r   r     s6     ##$//-. %tzz.'ABr#   c                 f   	 t        j                  | t         j                  t         j                  z  t         j                  z  d      }t        j
                  |d      5 }|j                  |       ddd       y# 1 sw Y   yxY w# t        t        f$ r}t        | |j                        d}~ww xY w)z/Creates a tracker file, storing the input data.i  wNF)r9   re   O_WRONLYO_CREATO_TRUNCfdopenr   rh   OSError#RaiseUnwritableTrackerFileExceptionr   )rw   datafdtfr   s        r$   r   r   +  s    M	"BKK"**$<rzz$I
B	2s	rhhtn 
 

7	 M
-.?
LLMs6   AB A:1B :B?B B B0B++B0c                     	 t        j                  |      }t        | |       y# t        $ r}t        | |j                        d}~ww xY w)zrCreate a tracker file and write json data to it.

  Raises:
    TypeError: If the data is not JSON serializable
  N)rf   r   	TypeErrorr   r   r   )rw   r   json_strerrs       r$   WriteJsonDataToTrackerFiler   7  sI    Ozz$H %x0 
 O
-.?
NNOs   $ 	AAAc                 >   d}d}d}	 t        | d      }|j                         }t        j                  |      }|t           |k7  rd}d}n=|t
           |r|j                          |r|j                  d|        |rt        |        S S 	 |r|j                          |r|j                  d|        |rt        |        yy# t        $ rD}|j                  t        j                  k7  r|j                  d| |j                         Y d}~}d}~wt        t        f$ rL}d}|d}n;cY d}~|r|j                          |r|j                  d|        |rt        |        S S Y d}~d}~ww xY w# |r|j                          |r|j                  d|        |rt        |        w w xY w)a  Reads tracker data from an upload tracker file if it exists.

  Deletes the tracker file if it uses an old format or the desired
  encryption key has changed.

  Args:
    tracker_file_name: Tracker file name for this upload.
    logger: logging.Logger for outputting log messages.
    encryption_key_sha256: Encryption key SHA256 for use in this upload, if any.

  Returns:
    Serialization data if the tracker file already exists (resume existing
    upload), None otherwise.
  NFrb   TzUpload tracker file (%s) does not match current encryption key. Restarting upload from scratch with a new tracker file that uses the current encryption key.zKCouldn't read upload tracker file (%s): %s. Restarting upload from scratch.)re   r   rf   r   ENCRYPTION_UPLOAD_TRACKER_ENTRY"SERIALIZATION_UPLOAD_TRACKER_ENTRYrj   r   r\   rh   r   r   r   KeyErrorri   )	rw   r   r   r_   remove_tracker_fileencryption_restarttracker_datatracker_jsonr   s	            r$   GetUploadTrackerDatar   D  s    ,#+)3/L$$&L::l+L348MM <=& kk78IK )* 9 * kk78IK )* 3 
 A 	ww%,,kk!"3QZZA J	  ( kk78IK )*   kk78IK )* sN   A
B= E& =	E#:D E& E#EE# E& E& E##E& &6Fc                 *    t        t        | |fz        )z:Raises an exception when unable to write the tracker file.)r   &TRACKER_FILE_UNWRITABLE_EXCEPTION_TEXT)rw   	error_strs     r$   r   r     s    ?+Y78 	9 9r#   )NNrz   )NNNNNNNN)2__doc__
__future__r   r   r   r   r   r-   rf   r9   rC   r   r)   botor   gslib.exceptionr   gslib.utils.boto_utilr	   r
   gslib.utils.constantsr   gslib.utils.hashing_helperr   gslib.utils.system_utilr   ru   r   r   r   objectr   r4   r=   rL   rZ   r`   r]   rE   r\   r   r   r   r   r   r   r   r   r   r   r"   r#   r$   <module>r      s   7 & %  '    	 	 
 
  , 3 4 & - 5
  # C '
 #: %9 "f ?8L6  $%)	0Ff$& 6:(V(! *.$()-%)-1-1-1!%@FBG( 37V'| (,CLC$	M
18+v9r#   