
    "<                         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mZ ddl	Z	dZ
d	Zd
 Zd Z G d de      Z G d de      Zd Zd Z	 ddZy)z.Wrapper for Cloud Run TrafficTargets messages.    )absolute_import)division)print_function)unicode_literalsN)traffic-z, c                 B    | t         k(  rt         S dj                  |       S )Nz{}%)_MISSING_PERCENT_OR_TAGSformatpercents    .lib/googlecloudsdk/api_lib/run/traffic_pair.py_FormatPercentager   #   s     ((##<<      c                 &    t        d | D              S )z'Sums the percents of the given targets.c              3   N   K   | ]  }|j                   s|j                     y wNr   .0ts     r   	<genexpr>z_SumPercent.<locals>.<genexpr>,   s     51199QYY   %%)sum)targetss    r   _SumPercentr   *   s    	55	55r   c                       e Zd ZdZddZy)
TrafficTaga  Contains the spec and status state for a traffic tag.

  Attributes:
    tag: The name of the tag.
    url: The tag's URL, or an empty string if the tag does not have a URL
      assigned yet. Defaults to an empty string.
    inSpec: Boolean that is true if the tag is present in the spec. Defaults to
      False.
    inStatus: Boolean that is true if the tag is present in the status. Defaults
      to False.
  c                 <    || _         || _        || _        || _        y)zReturns a new TrafficTag.

    Args:
      tag: The name of the tag.
      url: The tag's URL.
      in_spec: Boolean that is true if the tag is present in the spec.
      in_status: Boolean that is true if the tag is present in the status.
    N)tagurlinSpecinStatus)selfr   r    in_spec	in_statuss        r   __init__zTrafficTag.__init__<   s      DHDHDKDMr   N) FF)__name__
__module____qualname____doc__r&    r   r   r   r   /   s    
r   r   c                       e Zd ZdZ	 ddZed        Zed        Zed        Zed        Z	ed        Z
ed        Zed	        Zed
        Zed        Zd Zed        Zed        Zed        Zed        Zy)TrafficTargetPaira<
  Holder for TrafficTarget status information.

  The representation of the status of traffic for a service
  includes:
    o User requested assignments (spec.traffic)
    o Actual assignments (status.traffic)

  Each of spec.traffic and status.traffic may contain multiple traffic targets
  that reference the same revision, either directly by name or indirectly by
  referencing the latest ready revision.

  The spec and status traffic targets for a revision may differ after a failed
  traffic update or during a successful one. A TrafficTargetPair holds all
  spec and status TrafficTargets that reference the same revision by name or
  reference the latest ready revision. Both the spec and status traffic targets
  can be empty.

  The latest revision can be included in the spec traffic targets
  two ways
    o by revisionName
    o by setting latestRevision to True.

  Managed cloud run provides a single combined status traffic target
  for both spec entries with:
    o revisionName set to the latest revision's name
    o percent set to combined percentage for both spec entries
    o latestRevision not set

  In this case both spec targets are paired with the combined status
  target and a status_percent_override value is used to allocate the
  combined traffic.

  Attributes:
    key: Either the referenced revision name or 'LATEST' if the traffic targets
      reference the latest ready revision.
    latestRevision: Boolean indicating if the traffic targets reference the
      latest ready revision.
    revisionName: The name of the revision referenced by these traffic targets.
    specPercent: The percent of traffic allocated to the referenced revision
      in the service's spec.
    statusPercent: The percent of traffic allocated to the referenced revision
      in the service's status.
    specTags: Tags assigned to the referenced revision in the service's spec as
      a comma and space separated string.
    statusTags: Tags assigned to the referenced revision in the service's status
      as a comma and space separated string.
    urls: A list of urls that directly address the referenced revision.
    tags: A list of TrafficTag objects containing both the spec and status
      state for each traffic tag.
    displayPercent: Human-readable representation of the current percent
      assigned to the referenced revision.
    displayRevisionId: Human-readable representation of the name of the
      referenced revision.
    displayTags: Human-readable representation of the current tags assigned to
      the referenced revision.
    serviceUrl: The main URL for the service.
  c                 f    || _         || _        || _        || _        || _        || _        d| _        y)a  Creates a new TrafficTargetPair.

    Args:
      spec_targets: A list of spec TrafficTargets that all reference the same
        revision, either by name or the latest ready.
      status_targets: A list of status TrafficTargets that all reference the
        same revision, either by name or the latest ready.
      revision_name: The name of the revision referenced by the traffic targets.
      latest: A boolean indicating if these traffic targets reference the latest
        ready revision.
      status_percent_override: Percent to use for the status percent of this
        TrafficTargetPair, overriding the values in status_targets.
      service_url: The main URL for the service. Optional.

    Returns:
      A new TrafficTargetPair instance.
    N)_spec_targets_status_targets_revision_name_latest_status_percent_override_service_url_tags)r#   spec_targetsstatus_targetsrevision_namelateststatus_percent_overrideservice_urls          r   r&   zTrafficTargetPair.__init__   s:    ( &D)D'DDL$;D!#DDJr   c                 d    | j                   rt        j                  S t        j                  |       S r   )latestRevisionr   LATEST_REVISION_KEYGetKeyr#   s    r   keyzTrafficTargetPair.key   s.     "" '' >(/t(<>r   c                     | j                   S )zBReturns true if the traffic targets reference the latest revision.)r3   rA   s    r   r>   z TrafficTargetPair.latestRevision   s     <<r   c                     | j                   S r   )r2   rA   s    r   revisionNamezTrafficTargetPair.revisionName   s    r   c                 v    | j                   r(t        j                  t        | j                               S t        S r   )r0   six	text_typer   r
   rA   s    r   specPercentzTrafficTargetPair.specPercent   s+    ]];t'9'9:;;%%r   c                     | j                   t        j                  | j                         S | j                  r(t        j                  t	        | j                              S t
        S r   )r4   rG   rH   r1   r   r
   rA   s    r   statusPercentzTrafficTargetPair.statusPercent   sL    $$0]]48899			]];t';';<==%%r   c                 t    t         j                  t        d | j                  D                    }|r|S t        S )Nc              3   N   K   | ]  }|j                   s|j                     y wr   r   r   s     r   r   z-TrafficTargetPair.specTags.<locals>.<genexpr>   s     :0AEEquu0r   )_TAGS_JOIN_STRINGjoinsortedr0   r
   )r#   	spec_tagss     r   specTagszTrafficTargetPair.specTags   s4    !&&:d00::<I!9?'??r   c                 t    t         j                  t        d | j                  D                    }|r|S t        S )Nc              3   N   K   | ]  }|j                   s|j                     y wr   rN   r   s     r   r   z/TrafficTargetPair.statusTags.<locals>.<genexpr>   s     <2aeequu2r   )rO   rP   rQ   r1   r
   )r#   status_tagss     r   
statusTagszTrafficTargetPair.statusTags   s4    #((<d22<<>K%;C+CCr   c                 :    t        d | j                  D              S )Nc              3   N   K   | ]  }|j                   s|j                     y wr   )r    r   s     r   r   z)TrafficTargetPair.urls.<locals>.<genexpr>   s     ?!5A!%%!5r   )rQ   r1   rA   s    r   urlszTrafficTargetPair.urls   s    ?!5!5???r   c                 R    | j                   | j                          | j                   S r   )r6   _ExtractTagsrA   s    r   tagszTrafficTargetPair.tags   s"    zz
::r   c                    i }| j                   D ]3  }|j                  st        |j                  d      ||j                  <   5 | j                  D ]  }|j                  s|j                  |v r||j                     }n/|j	                  |j                  t        |j                              }|j
                  |j
                  nd|_        d|_         t        |j                         t        j                  d            | _        y)zEExtracts the traffic tag state from spec and status into TrafficTags.T)r$   Nr'   r   rB   )r0   r   r   r1   
setdefaultr    r"   rQ   valuesoperator
attrgetterr6   )r#   r]   spec_targetstatus_targetr   s        r   r\   zTrafficTargetPair._ExtractTags   s    D))__($Gd;?? * --			d	"=$$%oom//M<M<M1NO%2%6%6%B!!cgcl . 8+>+>u+EFDJr   c                     | j                   | j                  k(  rt        | j                         S dj                  t        | j                        t        | j                               S )z(Returns human readable revision percent.z{:4} (currently {}))rK   rI   r   r   rA   s    r   displayPercentz TrafficTargetPair.displayPercent   sX     T---t1122"))
D,,
-
D..
/1 1r   c                 |    | j                   r%t        j                  |       d| j                  dS | j                  S )z+Returns human readable revision identifier.z (currently ))r>   r   r@   rE   rA   s    r   displayRevisionIdz#TrafficTargetPair.displayRevisionId   s:     $+NN4$8$($5$57 7 r   c                 z    | j                   }| j                  }||k(  r|t        k7  r|S dS dj                  ||      S )Nr'   z{} (currently {}))rS   rW   r
   r   )r#   rR   rV   s      r   displayTagszTrafficTargetPair.displayTags  sB    I//KK'+CC[KK ''	;??r   c                     | j                   S )zThe main URL for the service.)r5   rA   s    r   
serviceUrlzTrafficTargetPair.serviceUrl  s     r   Nr'   )r(   r)   r*   r+   r&   propertyrB   r>   rE   rI   rK   rS   rW   rZ   r]   r\   rg   rj   rl   rn   r,   r   r   r.   r.   K   s$   8J ,.8 > >     & & & & @ @
 D D
 @ @  
G$ 1 1   @ @  r   r.   c                     d}|rTt         j                  | v rBt         j                  |vr0||v r,||   }||t         j                  <   || v rt        |      }|S ||= |S )a  Splits the fully-managed latest status target.

  For managed the status target for the latest revision is
  included by revisionName only and may hold the combined traffic
  percent for both latestRevisionName and latestRevision spec targets.
  Here we adjust keys in status_dict to match with spec_dict.

  Args:
    spec_dict: Dictionary mapping revision name or 'LATEST' to the spec
      traffic target referencing that revision.
    status_dict: Dictionary mapping revision name or 'LATEST' to the status
      traffic target referencing that revision. Modified by this function.
    is_platform_managed: Boolean indicating if the current platform is Cloud Run
      fully-managed.
    latest_ready_revision_name: The name of the latest ready revision.

  Returns:
    Optionally, the id of the list of status targets containing the combined
    traffic referencing the latest ready revision by name and by latest.
  N)r   r?   id)	spec_dictstatus_dictis_platform_managedlatest_ready_revision_namecombined_status_targets_idlatest_status_targetss         r   _SplitManagedLatestStatusTargetry     sy    ,  $g99YF!!4 K/'(BC/DK++,!Y.#%&;#<  
$# 0
1	##r   c                     d}t        |      |k(  rOt        |t        j                           }t        |      }t	        ||      }| t        j                  k(  r|}|S ||z
  }|S )zFComputes the optional override percent to apply to the status percent.N)rr   r   r   r?   min)rB   rs   r8   rw   percent_overridespec_by_latest_percentstatus_percentstatus_by_latest_percents           r   _PercentOverrider   6  sv     55(73N3N)OP 0N"#9>J
g)))1 
 (*BB	r   c                    t        |       }t        |      }t        ||||      }g }t        |      j                  |      D ]o  }	|j	                  |	g       }
|j	                  |	g       }t        |	|||      }|	t        j                  k(  r|}d}n|	}d}|j                  t        |
|||||             q t        |t        j                        S )a  Returns a list of TrafficTargetPairs for a Service.

  Given the spec and status traffic targets wrapped in a TrafficTargets instance
  for a sevice, this function pairs up all spec and status traffic targets that
  reference the same revision (either by name or the latest ready revision) into
  TrafficTargetPairs. This allows the caller to easily see any differences
  between the spec and status traffic.

  For fully-managed Cloud Run, the status target for the latest revision is
  included by revisionName only and may hold the combined traffic
  percent for both latestRevisionName and latestRevision spec targets. This
  function splits the fully-managed status target for the latest revision into
  a target for the percent allocated to the latest revision by name and a target
  for the percent allocated to the latest revision because it is latest.

  Args:
    spec_traffic: A traffic.TrafficTargets instance wrapping the spec traffic.
    status_traffic: A traffic.TrafficTargets instance wrapping the status
      traffic.
    is_platform_managed: Boolean indicating whether the current platform is
      fully-managed or Anthos/GKE.
    latest_ready_revision_name: The name of the service's latest ready revision.
    service_url: The main URL for the service. Optional.
  Returns:
    A list of TrafficTargetPairs representing the current state of the service's
    traffic assignments. The TrafficTargetPairs are sorted by revision name,
    with targets referencing the latest ready revision at the end.
  TFr_   )dictry   setuniongetr   r   r?   appendr.   rQ   SortKeyFromTarget)spec_trafficstatus_trafficru   rv   r<   rs   rt   rw   resultkr7   r8   r|   r9   r:   s                  r   GetTrafficTargetPairsr   E  s    F < )^$+>13M O&y>,a==B'L __Q+N'9n(BDG'''0mfmf
MM,v*K	9: - 
G55	66r   ro   )r+   
__future__r   r   r   r   rb   googlecloudsdk.api_lib.runr   rG   r
   rO   r   r   objectr   r.   ry   r   r   r,   r   r   <module>r      sk    5 &  % '  . 
    !6
 8E EP $F  CE87r   