
    d5                        d 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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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dlmZ g dZg dZ dgZ! G d dejD                        Z#d Z$d Z%d Z&d Z'd  Z(d! Z)d" Z*ejV                   G d# d$ejX                               Z-y)%zDImplementation of Unix-like cat command for cloud storage providers.    )absolute_import)division)unicode_literalsN)	cloud_api)arg_parsers)base)errors)errors_util)flags)stdin_iterator)storage_url)user_request_args_factory)wildcard_iterator)task_executor)task_graph_executor)task_status)restore_bucket_task)bulk_restore_objects_task)restore_object_task)log)allow_overwritecreated_after_timecreated_before_timedeleted_after_timedeleted_before_time)all_versionsr   r   r   r   r   asyncronousr   c                       e Zd ZdZdZy)ExecutionModeAsynchronousSynchronousN)__name__
__module____qualname__ASYNCHRONOUSSYNCHRONOUS     lib/surface/storage/restore.pyr   r   @   s    ,+r(   r   c                     |D ]=  }t        | |      st        j                  dj                  |j                  |             y)aR  Raises error if invalid combination of flags found in user input.

  Args:
    args (parser_extensions.Namespace): User input object.
    execution_mode (ExecutionMode): Determined by presence of --async flag.
    invalid_flags (list[str]): Flags as `args` attributes.

  Raises:
    error.Error: Flag incompatible with execution mode.
  zB{} execution does not support flag: {}. See help text with --help.N)getattrr	   Errorformatvalue)argsexecution_modeinvalid_flagsinvalid_flags       r)   "_raise_if_invalid_flag_combinationr3   E   sC     $lt\"LL((.""L)  $r(   c                     t        |       rag }t        D ]   }t        ||      s|j                  |       " |r3t	        j
                  dj                  dj                  |                  yy)zRaises error if invalid combination of flags found in user input for bucket restore.

  Args:
    url: CloudUrl object.
    args: (parser_extensions.Namespace): User input object.

  Raises:
    Error: Flags incompatible with execution mode.
  zSBucket restore does not support the following flags: {}. See help text with --help.z, N)_is_bucket_restore_INVALID_BUCKET_RESTORE_FLAGSr+   appendr	   r,   r-   join)urlr/   invalid_flags_foundr2   s       r)   0_raise_error_if_invalid_flags_for_bucket_restorer;   Z   sm     5	|	$""<0 6 LL((.tyy9L/M(N   r(   c                     t        | t        j                        xr2 | j                         xr  t	        j
                  | j                         S )N)
isinstancer   CloudUrl	is_bucketr   contains_wildcard
url_string)r9   s    r)   r5   r5   r   sA    k**+ B
--/B11#..A
Ar(   c              #      K   t        j                  | j                  | j                        D ]I  }t	        j
                  |d      }t        ||        t        j                  | j                  |       | K yw)z%Extracts, validates, and yields URLs.T)is_bucket_gen_parsing_allowedN)
r   get_urls_iterableurlsread_paths_from_stdinr   storage_url_from_stringr;   r
   raise_error_if_not_gcscommand_path)r/   rA   r9   s      r)   _url_iteratorrJ   z   sh     "44
ii++j 
-
-$C 5S$?&&t'8'8#>
Is   A8A:c              #   B  K   t        j                  t              }t        |       D ]  }t	        j
                  |j                        s$t        j                  dj                  |             |t        j                  |j                  |j                           j                  |j                          |j!                         D ]V  \  }}t#        j$                  ||| j&                  | j(                  | j*                  | j,                  | j.                  |       X yw)z"Yields non-blocking restore tasks.zBulk restores are long operations. For restoring a single object, you should probably use a synchronous restore without the --async flag. URL without wildcards: {})r   r   r   r   r   user_request_argsN)collectionsdefaultdictlistrJ   r   r@   rA   r   warningr-   r   r>   schemebucket_namer7   resource_nameitemsr   BulkRestoreObjectsTaskr   r   r   r   r   )r/   rL   bucket_to_globsr9   
bucket_urlobject_globss         r)   _async_restore_task_iteratorrY      s     ++D1/4 c..s~~>	kkAAG
 K((S__EFMM ! #2"7"7"9j,
#
:
:,,22 4422 44+	 	 #:s   DDc           	   #     K   d}t        |       D ]  }t        |      rt        j                  |       't	        t        j                  |j                  |t        j                  j                  d            }|s.t        j                  dj                  |j                              |D ]p  }| j                  rt        j                   ||       (|rE|j"                  j$                  |j"                  j$                  k7  rt        j                   ||       |}r  |rt        j                   ||       yyw)zYields blocking restore tasks.NT)fields_scopeobject_state
files_onlyz*The following URLs matched no objects:
-{})rJ   r5   r   RestoreBucketTaskrO   r   get_wildcard_iteratorrA   r   ObjectStateSOFT_DELETEDr	   InvalidUrlErrorr-   r   r   RestoreObjectTaskr   versionless_url_string)r/   r[   rL   last_resourcer9   	resourcesresources          r)   _sync_restore_task_iteratorrh      s*    -4 c#11#66//NN%"..;;		
I ""
7
>
>s~~
N  			!33H>OPP ))@@##::; $55.  ! ! !: 

/
/(  s   D=D?c                 ,   | j                   rt        j                  j                  }nt        j                  j                  }t        j                  | t
        j                  j                        }| j                  rt        | |      S t        | ||      S )zYields restore tasks.)metadata_type)preserve_aclr   FieldsScopeFULLSHORTr   'get_user_request_args_from_command_argsMetadataTypeOBJECTr   rY   rh   )r/   r[   rL   s      r)   _restore_task_iteratorrr      s{    	((--L((..LGG
7DDKK 
 
'.?@@	$T<9J	KKr(   c                   0    e Zd ZdZdddZed        Zd Zy)Restorez)Restore one or more soft-deleted objects.z_
      The restore command restores soft-deleted resources:

        $ {command} url...

      ab	  

      Restore soft-deleted version of bucket with generations:

        $ {command} gs://bucket#123

      Restore several soft-deleted buckets with generations:

        $ {command} gs://bucket1#123 gs://bucket2#456

      Restore latest soft-deleted version of object in a bucket.

        $ {command} gs://bucket/file1.txt

      Restore a specific soft-deleted version of object in a bucket by specifying the generation.

        $ {command} gs://bucket/file1.txt#123

      Restore all soft-deleted versions of object in a bucket.

        $ {command} gs://bucket/file1.txt --all-versions

      Restore several objects in a bucket (with or without generation):

        $ {command} gs://bucket/file1.txt gs://bucket/file2.txt#456

      Restore the latest soft-deleted version of all text objects in a bucket:

        $ {command} gs://bucket/**.txt

      Restore a list of objects read from stdin (with or without generation):

        $ cat list-of-files.txt | {command} --read-paths-from-stdin

      Restore object with its original ACL policy:

        $ {command} gs://bucket/file1.txt --preserve-acl

      Restore all objects in a bucket asynchronously:

        $ {command} gs://bucket/** --async

      Restore all text files in a bucket asynchronously:

        $ {command} gs://bucket/**.txt --async

      Restore objects created within a specific time range:

        $ {command} gs://bucket/** --async             --created-after-time="2023-01-01T00:00:00Z"             --created-before-time="2023-01-31T23:59:59Z"

      Restore objects soft-deleted within a specific time range:

        $ {command} gs://bucket/** --async             --deleted-after-time="2023-01-01T00:00:00Z"             --deleted-before-time="2023-01-31T23:59:59Z"

      Restore objects using a combination of creation and deletion time filters:

          $ {command} gs://bucket/** --async --allow-overwrite               --created-after-time="2023-01-01T00:00:00Z"               --deleted-after-time="2023-01-01T00:00:00Z"

      This command filters the objects that were live at 2023-01-01T00:00:00Z
      and then soft-deleted afterwards. This combination of filters is
      especially helpful if there is a period of erroneous overwrites.
      They allow you to go back to the point just before the overwrites began.
      You will also need to set the `--allow-overwrite` option to true.
      )DESCRIPTIONEXAMPLESc                    | j                  ddd       t        j                  |        t        j                  |        t        j                  |        | j                  d      }|j                  ddd	d
       | j                  ddd	d       | j                  d      }|j                  dt        j                  j                  d       |j                  dt        j                  j                  d       |j                  dd	d       |j                  dt        j                  j                  d       |j                  dt        j                  j                  d       y )NrE   *zThe url of objects to list.)nargshelpzSYNCHRONOUS RESTORE OPTIONS)rz   z-az--all-versions
store_truea  Restores all versions of soft-deleted objects.

This flag is only useful for buckets with [object versioning] (https://cloud.google.com/storage/docs/object-versioning) enabled. In this case, the latest soft-deleted version will become live and the previous generations will become noncurrent.

If versioning is disabled, the latest soft-deleted version will become live and previous generations will be soft-deleted again.

This flag disables parallelism to preserve version order.)actionrz   z--asyncr   zIInitiates an asynchronous bulk restore operation on the specified bucket.)destr|   rz   zBULK RESTORE OPTIONSz--created-after-timez<Restores only the objects that were created after this time.)typerz   z--created-before-timez=Restores only the objects that were created before this time.z--allow-overwritezIf included, live objects will be overwritten. If versioning is enabled, this will result in a noncurrent object. If versioning is not enabled, this will result in a soft-deleted object.z--deleted-after-timezARestores only the objects that were soft-deleted after this time.z--deleted-before-timezBRestores only the objects that were soft-deleted before this time.)	add_argumentr   add_precondition_flagsadd_preserve_acl_flagadd_read_paths_from_stdin_flag	add_groupr   DatetimeParse)parsersynchronous_restore_flag_groupbulk_restore_flag_groups      r)   ArgszRestore.Args,  s   
c0MN	  (	'	((0%+%5%5* &6 &" #//L 0 "   	 %..4J.K((!!''K ) 
 ((!!''L ) 
 ((J	 )  ((!!''O	 )  ((!!''P	 ) r(   c           	         t         j                  j                         }|j                  r t	        |t
        j                  t               nt	        |t
        j                  t               t        j                  t        |      |j                   |t        j                  t        j                   j"                  d             | _        y )N)increment_typemanifest_path)task_iteratorparallelizabletask_status_queueprogress_manager_args)r   multiprocessing_contextQueuer   r3   r   r%   _SYNCHRONOUS_RESTORE_FLAGSr&   _BULK_RESTORE_FLAGSr   execute_tasksrr   r   r   ProgressManagerArgsIncrementTypeINTEGER	exit_code)selfr/   r   s      r)   RunzRestore.Runt  s    +CCIIK(
**,F )
))+> #00,T2,,,+)==&44<<D
	DNr(   N)r"   r#   r$   __doc__detailed_helpstaticmethodr   r   r'   r(   r)   rt   rt      s5    1
E
M-^ E ENr(   rt   ).r   
__future__r   r   r   rM   enumgooglecloudsdk.api_lib.storager   googlecloudsdk.callioper   r   "googlecloudsdk.command_lib.storager	   r
   r   r   r   r   r   (googlecloudsdk.command_lib.storage.tasksr   r   r   0googlecloudsdk.command_lib.storage.tasks.bucketsr   0googlecloudsdk.command_lib.storage.tasks.objectsr   r   googlecloudsdk.corer   r   r6   r   Enumr   r3   r;   r5   rJ   rY   rh   rr   UniverseCompatibleCommandrt   r'   r(   r)   <module>r      s    K &  '   4 / ( 5 : 4 = : H @ B H @ P V P # !  -- DII 
*0
6#LL  odll o or(   