
    $                         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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dZdZdZdZdZd Zd Zd Z	 ddZd Z	 	 	 	 	 	 ddZd Zd Zd Zy)z0Utilities for the cloud deploy rollout resource.    )
exceptions)client_util)release)rollout)log)	resourceszBclouddeploy.projects.locations.deliveryPipelines.releases.rolloutszMapprovalState="NEEDS_APPROVAL" AND state="PENDING_APPROVAL" AND targetId="{}"zg(approvalState!="REJECTED" AND approvalState!="NEEDS_APPROVAL") AND state="SUCCEEDED" AND targetId="{}"ztargetId="{}"z{}-to-{}-{:04d}z{}/releases/-zDeployEndTime desczCreateTime desczEnqueueTime descc                 L    t         j                  j                  | t              S )zReturns a rollout reference object from a rollout message.

  Args:
    rollout_name: str, full canonical resource name of the rollout

  Returns:
    Rollout reference object
  
collection)r   REGISTRYParseRelativeName_ROLLOUT_COLLECTION)rollout_names    5lib/googlecloudsdk/command_lib/deploy/rollout_util.pyRolloutReferenceFromNamer   .   s(     
			-	-2 
. 
     c                 x    | }d| v r3t         j                  j                  | t              j	                         }|S )zqReturns rollout ID.

  Args:
    rollout_name_or_id: str, rollout full name or ID.

  Returns:
    Rollout ID.
  z	projects/r
   )r   r   r   r   Name)rollout_name_or_id
rollout_ids     r   	RolloutIdr   <   sE     "*&&##55': 6 
df  
r   c                     t         j                  | j                               }t        j                  |j	                               }t        j                         j                  ||t              S )a  Lists the rollouts in PENDING_APPROVAL state for the releases associated with the specified target.

  The rollouts must be approvalState=NEEDS_APPROVAL and
  state=PENDING_APPROVAL. The returned list is sorted by rollout's create
  time.

  Args:
    target_ref: protorpc.messages.Message, target object.
    pipeline_ref: protorpc.messages.Message, pipeline object.

  Returns:
    a sorted list of rollouts.
  )release_name
filter_strorder_by)	 PENDING_APPROVAL_FILTER_TEMPLATEformatr   WILDCARD_RELEASE_NAME_TEMPLATERelativeNamer   RolloutClientListPENDING_ROLLOUT_ORDERBY)
target_refpipeline_refr   parents       r   ListPendingRolloutsr&   N   s^     066z7HI*)001J1J1LM&				 	%	%& 
& 
 r   Nc                     t         j                  |j                               }t        j                         j                  ||j                  | j                               |||      S )a/  Gets successfully deployed rollouts for the releases associated with the specified target and index.

  Args:
    target_ref: protorpc.messages.Message, target object.
    pipeline_ref: protorpc.messages.Message, pipeline object.
    filter_str: Filter string to use when listing rollouts.
    order_by: order_by field to use when listing rollouts.
    page_size: int, the maximum number of objects to return per page.
    limit: int, the maximum number of `Rollout` objects to return.

  Returns:
    a rollout object or None if no rollouts in the target.
  )r   r   r   	page_sizelimit)r   r   r   r   r    r!   r   )r#   r$   r   r   r(   r)   r%   s          r   GetFilteredRolloutsr*   f   s_      *001J1J1LM&				 	%	%"":??#45 
& 
 r   c                 <   t         j                  |       }	 t        j                         j	                  |j                         |      }t        |j                         | |      S # t        j                  $ r$ t        j                  |j                               w xY wN)!ROLLOUT_IN_TARGET_FILTER_TEMPLATEr   r   r    r!   r   ComputeRolloutIDr   apitools_exceptions	HttpErrorcd_exceptionsListRolloutsError)	to_targetrelease_refr   rolloutss       r   GenerateRolloutIdr6      s    077	B*F$$&++  "JH K,,.	8DD		&	& F

)
)+*B*B*D
EEFs   AA$ $7Bc           	      B   |}|st        ||       }| j                         }	t        j                  j	                  |t
        |	j                  d      |	j                  d      |	j                  d      | j                         d      }
t        j                         j                  |
j                         ||      }t        j                  j                  dj                  |
j                         |             t!        j"                         j%                  |
|||||      }t        j                  j'                  |j(                  d	      }t        j*                         j-                  ||d
       t!        j"                         j/                  |
j                               S )a  Creates a rollout by calling the rollout create API and waits for the operation to finish.

  Args:
    release_ref: protorpc.messages.Message, release resource object.
    to_target: str, the target to create create the rollout in.
    rollout_id: str, rollout ID.
    annotations: dict[str,str], a dict of annotation (key,value) pairs that
      allow clients to store small amounts of arbitrary data in cloud deploy
      resources.
    labels: dict[str,str], a dict of label (key,value) pairs that can be used to
      select cloud deploy resources and to find collections of cloud deploy
      resources that satisfy certain conditions.
    description: str, rollout description.
    starting_phase_id: str, rollout starting phase.
    override_deploy_policies: List of Deploy Policies to override.

  Raises:
      ListRolloutsError: an error occurred calling rollout list API.

  Returns:
    The rollout resource created.
  
projectsIdlocationsIddeliveryPipelinesId)r8   r9   r:   
releasesId)r   params)nametargetIddescriptionz Creating rollout {} in target {}z)clouddeploy.projects.locations.operationsr
   z2Waiting for rollout creation operation to complete)r6   AsDictr   r   Parser   getr   r   GetMessagesModuleRolloutr   r   statusPrintr   r   r    Creater   r=   OperationsClientWaitForOperationGet)r4   r3   r   annotationslabelsr?   starting_phase_idoverride_deploy_policiesfinal_rollout_idresource_dictrollout_refrollout_obj	operationoperation_refs                 r   CreateRolloutrU      s   @  	(K@$$&-""(($%)),7&**=9!.!2!23H!I#((*	 ) 	+ --/77##% 8 + **(//

"
"
$i
 ##%,,) $$66nn!L 7 -  11:
 
			 	$	$[%=%=%?	@@r   c                     t        | |t        t        dd      }g }|D ]C  }|s|j                  |       nt	        |      s|j                  |       t        |      dk\  sB |S  |S )a  Gets the currently deployed release and the next valid release that can be rolled back to.

  Args:
    target_ref: protorpc.messages.Message, target resource object.
    pipeline_ref: protorpc.messages.Message, pipeline resource object.

  Raises:
      HttpException: an error occurred fetching a resource.

  Returns:
    An list containg the currently deployed release and the next valid
    deployable release.
  N
   )r#   r$   r   r   r)   r(      )r*    DEPLOYED_ROLLOUT_FILTER_TEMPLATESUCCEED_ROLLOUT_ORDERBYappend_RolloutIsFromAbandonedReleaselen)r#   r$   iterabler5   rR   s        r   GetValidRollBackCandidater_      so     !1&( (kook"+K8ook"
8}	/  
/r   c                 (   t        | j                        }|j                         }	 t        j                         j                  |j                               }|j                  S # t        j                  $ r}t        j                  |      d }~ww xY wr,   )r   r=   Parentr   ReleaseClientrJ   r   r/   r0   r   HttpException	abandoned)rR   rQ   r4   release_objerrors        r   r\   r\      s~    ()9)9:+""$+*'')--k.F.F.HIK 
		 
	&	& *

"
"5
))*s   1A$ $B7BBc                     |D ch c]  }t        |j                         }}t        dd      D ]!  }t        j	                  | ||      }||vs|c S  t        j                  |       c c}w )ar  Generates a rollout ID.

  Args:
    release_id: str, release ID.
    target_id: str, target ID.
    rollouts: [apitools.base.protorpclite.messages.Message], list of rollout
      messages.

  Returns:
    rollout ID.

  Raises:
    googlecloudsdk.command_lib.deploy.exceptions.RolloutIdExhaustedError: if
    there are more than 1000 rollouts with auto-generated ID.
     i  )r   r=   rangeROLLOUT_ID_TEMPLATEr   r1   RolloutIDExhaustedError)
release_id	target_idr5   rrollout_idsir   s          r   r.   r.     sm      -55Hq166"H+5D>a %++J	1EJ$  	--j99 6s   A()NN)NNNNNN) __doc__apitools.base.pyr   r/   "googlecloudsdk.api_lib.clouddeployr   r   r   googlecloudsdk.calliope!googlecloudsdk.command_lib.deployr1   googlecloudsdk.corer   r   r   r   rY   r-   rj   r   rZ   r"   ENQUEUETIME_ROLLOUT_ORDERBYr   r   r&   r*   r6   rU   r_   r\   r.    r   r   <module>ry      s    7 ? : 6 6 . I # ) I 1 !
O ! %4 !' !0 . + 0 $2 KO6F !KA\B:r   