
    m                     4   d Z ddlZddlZddlmZmZ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" 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l0m1Z1 ddl2m3Z3 ddl4m	Z5 ddl4m6Z6 ddl4m7Z7 ddl8m9Z9 ddl8m:Z: ddl;m<Z= ddl;m>Z> d Z? ej                  d!      ZAd"ZB ej                  d#      ZCd$ZDd%ZEd&ZFg d'ZGd(ZHd)ZId*ZJ e:j                  d+d,-      ZL e:j                  d.d/-      ZM e:j                  d0d1-      ZNeLeMeNgZOg d2ZPd3gePz   ZQd4ZRd5ZSd6ej                  d7eUd8ej                  fd9ZWd6ej                  d7eUd8ej                  fd:ZX	 dcd;ej                  d<ej                  d=e7j                  d7eUd>eeU   d8ej                  fd?Z\d;ej                  d<ej                  d=e7j                  d@eej                     d8eeej                     eeU   f   f
dAZ^d;ej                  d6ej                  d@eej                     d8eej                  eeU   f   fdBZ`dCeUd8eeU   fdDZadEeUd8eeU   fdFZbd;ej                  d6ej                  d@eej                     d8eeej                     eeU   f   fdGZdd;ej                  d6ej                  d8ej                  fdHZed;ej                  d6ej                  d8ej                  fdIZfd;ej                  d6ej                  dJeej                     d8eej                  eeU   f   fdKZhdLeUd8eUfdMZid;ej                  d<ej                  d=e7j                  d@eej                     d8eej                  eeU   f   f
dNZld;ej                  d@eej                     d8eeU   fdOZmd;ej                  d6ej                  d8eeej                     eeU   f   fdPZod;ej                  d6ej                  d8eeeU   eej                     eeU   f   fdQZqd;ej                  d8dfdRZrd;ej                  d6ej                  d@eej                     d8eeej                     eeU   f   fdSZtd;ej                  dTej                  d@eej                     d=e7j                  d8eeU   f
dUZud;ej                  dTej                  d@eej                     d8eeU   fdVZvdWeUd8ewfdXZxdYej                  d=e7j                  dTej                  d8dfdZZydYej                  d=e7j                  dTej                  d[eeU   d8df
d\Zz e>j                  d]d^_      d`        Z|d;ej                  daej                  d8ej                  fdbZ~y)dzHThis file provides the implementation of the `functions deploy` command.    N)	FrozenSetOptionalTuple)base_api)
exceptions)api_enablement)	cmek_util)secrets)util)client)types)storage_util)base)parser_extensions)ArgumentTypeError)flags)labels_util)run_util)secrets_config)service_account_util)source_util)deploy_util)serverless_operations)	arg_utils)map_util)log)	resources)
console_io)progress_tracker)files)retryz^There was a problem uploading the source code to a signed Cloud Storage URL. Please try again.zgs://([^/]+)/(.*)zNInvalid Cloud Storage URL. Must match the following format: gs://bucket/objectzhttps://source\.developers\.google\.com/projects/(?P<project_id>[^/]+)/repos/(?P<repo_name>[^/]+)(((/revisions/(?P<commit>[^/]+))|(/moveable-aliases/(?P<branch>[^/]+))|(/fixed-aliases/(?P<tag>[^/]+)))(/paths/(?P<path>[^/]+))?)?/?$aB  Invalid Cloud Source Repository URL provided. Must match the following format: https://source.developers.google.com/projects/<projectId>/repos/<repoName>. Specify the desired branch by appending /moveable-aliases/<branchName>, the desired tag with /fixed-aliases/<tagName>, or the desired commit with /revisions/<commit>. zD`--retry` is only supported with an event trigger not http triggers.zThe latest revision of this function is not serving 100% of traffic. Please see the associated Cloud Run service to confirm your expected traffic settings.))docker_registryz--docker-registry)security_levelz--security-level)buildpack_stackz--buildpack-stackz=`%s` is only supported in Cloud Functions (First generation).zdeployment-toolz
cli-gcloudz[ArtifactRegistry]ARTIFACT_REGISTRY)keyz[Healthcheck]SERVICE_ROLLBACKz[Triggercheck]TRIGGER_ROLLBACK)
kKiMMiGGiTTiPPima  
    ^                                    # Beginning of input marker.
    (?P<amount>\d+)                      # Amount.
    ((?P<suffix>[-/ac-zAC-Z]+)([bB])?)?  # Optional scale and optional 'b'.
    $                                    # End of input marker.
z
    ^                                    # Beginning of input marker.
    (?P<amount>\d*.?\d*)                 # Amount.
    (?P<suffix>[-/ac-zAC-Z]+)?           # Optional scale.
    $                                    # End of input marker.
messagessourcereturnc                     t         j                  |      }|st        j                  t              | j                  | j                  |j                  d      |j                  d                  S )zConstructs a `Source` message from a Cloud Storage object.

  Args:
    messages: messages module, the GCFv2 message stubs.
    source: the Cloud Storage URL.

  Returns:
    The resulting cloudfunctions_v2_messages.Source.
        bucketobjectstorageSource)_GCS_SOURCE_REGEXmatchr   FunctionsError_GCS_SOURCE_ERROR_MESSAGESourceStorageSourcegroup)r4   r5   r@   s      =lib/googlecloudsdk/command_lib/functions/v2/deploy/command.py_GetSourceGCSrG      sg     
!
!&
)%	

#
#$=
>>	**QA +  
 
     c                    t         j                  |      }|t        j                  t              | j                  |j                  d      |j                  d      |j                  d            }|j                  d      }|j                  d      }|j                  d      }|r||_        n|r||_        n|xs d|_	        | j                  |	      S )
zConstructs a `Source` message from a Cloud Source Repository reference.

  Args:
    messages: messages module, the GCFv2 message stubs.
    source: the Cloud Source Repository reference.

  Returns:
    The resulting cloudfunctions_v2_messages.Source.
  
project_id	repo_namepath)	projectIdrepoNamedircommitbranchtagmaster)
repoSource)_CSR_SOURCE_REGEXr@   r   rA   _CSR_SOURCE_ERROR_MESSAGE
RepoSourcerE   	commitShatagName
branchNamerC   )r4   r5   r@   repo_sourcerP   rQ   rR   s          rF   _GetSourceCSRr\      s     
!
!&
)%
]

#
#$=
>>##L){{;'
++f
 $ + ;;x &;;x &E#"K
K $/xK	K	00rH   argsr   function_refkms_keyc                    |j                   }t        j                         5 }t        j                  ||| j
                        }| j                  rat        j                  ||| j                        }|j                  |j                  |j                  |j                              cddd       S |j                  |      }		 |j                  j                  |j                  |	|j!                         j#                                     }
t        j,                  ||
j.                         |j                  |
j0                        cddd       S # t$        j&                  $ r}t)        j*                  ||       |d}~ww xY w# 1 sw Y   yxY w)a  Constructs a `Source` message from a local file system path.

  Args:
    args: The arguments that this command was invoked with.
    client: The GCFv2 Base API client.
    function_ref: The GCFv2 functions resource reference.
    source: The source path.
    kms_key: resource name of the customer managed KMS key | None

  Returns:
    The resulting cloudfunctions_v2_messages.Source.
  r:   r=   N)
kmsKeyName)generateUploadUrlRequestparent)MESSAGES_MODULE
file_utilsTemporaryDirectoryr   CreateSourcesZipFileignore_filestage_bucketUploadToStageBucketrC   rD   r;   nameGenerateUploadUrlRequestprojects_locations_functionsGenerateUploadUrl@CloudfunctionsProjectsLocationsFunctionsGenerateUploadUrlRequestParentRelativeNameapitools_exceptions	HttpErrorr	   ProcessExceptionUploadToGeneratedUrl	uploadUrlr>   )r]   r   r^   r5   r_   r4   tmp_dirzip_file_pathdest_objectgenerate_upload_url_requestdestes               rF   _GetSourceLocalr}      sl   & ##($$&'44))M 33
t'8'8k __ .. ''0@0@ /    '& %-$E$E %F %!	22DDUU)D#**,99; V 
 &&}dnnE__4+=+=_>? '&2 !** ""1g.3 '&s7   BF0FAE;FF #E;;F  FFexisting_functionc           
         | j                   .|,|j                  j                   j                  rdt               fS | j                   xs d}|j                  }|j                  d      rt        ||      t        dg      fS |j                  d      rt        ||      t        dg      fS | j                  xs |j                  j                  }t        j                  ||       t        | |||t        | |            t        dg      fS )a  Parses the source bucket and object from the --source flag.

  Args:
    args: arguments that this command was invoked with.
    client: The GCFv2 API client
    function_ref: The GCFv2 functions resource reference.
    existing_function: `cloudfunctions_v2_messages.Function | None`,
      pre-existing function.

  Returns:
    A tuple `(function_source, update_field_set)` where
    - `function_source` is the resulting `cloudfunctions_v2_messages.Source`,
    - `update_field_set` is a set of update mask fields.
  N.zgs://zbuild_config.sourcezhttps://)r_   )r5   buildConfigrT   	frozensetrd   
startswithrG   r\   runtimer   (ValidateDirectoryHasRequiredRuntimeFilesr}   _GetActiveKmsKey)r]   r   r^   r~   r5   r4   r   s          rF   
_GetSourcer     s   * kk

'

'
'
.
.
9
9
 ;;#&##(w6*I7L6M,NNN$6*I7L6M,NNNllC/;;CCG88I '89 '()* *rH   c                 	   i }|r|j                   rt|j                   j                  r^|j                   j                  j                  r>|j                   j                  j                  D ]  }|j                  ||j                  <    t        j                  d|       }t        j                  |fi |}i }i }|rJ|j                   r>t        j                  |j                   j                  |j                   j                        }t        j                  |       rQ	 t        j                  || t        j                          t#        j$                  t        j                                      }n|}t        j0                  |      \  }
}t        j0                  |      \  }}t3        | ||      \  }}}t5        | |      \  }}t7        | dd      }t7        | dd      }t9               }| j:                  r|j=                  d       | j>                  |j=                  d       ||j=                  d       ||j=                  d       | j@                  | jB                  r|j=                  d	       | jD                  | jF                  r|j=                  d
       | jH                  | jJ                  |j=                  d       | jL                  |j=                  d       ||k7  r|j=                  d       ||
k7  r|j=                  d       ||k7  r|j=                  d       d}| jO                  d      r|j=                  d       n.| jO                  d      r| jP                  }|j=                  d       tR        jU                  |||      }|jW                  tY        | j>                        | jB                  rdn| j@                  | jF                  rdn| jD                  | jH                  xs | jJ                  | jL                  |||| j:                  xs d|jV                  j[                  t]        |j_                               D cg c],  \  }}|jV                  jZ                  ja                  ||      . c}}      t        jb                  ||      t        jd                  ||d      |tg        |      |      |fS # t&        $ r3}	t)        j*                  t-        j.                  |	             Y d}	~	d}	~	ww xY wc c}}w )a  Constructs a ServiceConfig message from the command-line arguments.

  Args:
    args: arguments that this command was invoked with.
    messages: messages module, the GCFv2 message stubs.
    existing_function: the existing function.

  Returns:
    A tuple `(service_config, updated_fields_set)` where
    - `service_config` is the resulting
    `cloudfunctions_v2_messages.ServiceConfig`.
    - `updated_fields_set` is a set of update mask fields.
  zenv-varsNconcurrencycpuz-service_config.all_traffic_on_latest_revisionzservice_config.available_memoryz/service_config.max_instance_request_concurrencyzservice_config.available_cpuz!service_config.max_instance_countz!service_config.min_instance_countz$service_config.service_account_emailzservice_config.timeout_secondsz$service_config.environment_variablesz+service_config.secret_environment_variableszservice_config.secret_volumesclear_binary_authorizationz*service_config.binary_authorization_policybinary_authorizationr&   valueadditionalPropertiesT)normalize_for_v2)availableMemorymaxInstanceCountminInstanceCountserviceAccountEmailtimeoutSecondsingressSettingsvpcConnectorvpcConnectorEgressSettingsallTrafficOnLatestRevisionenvironmentVariablessecretEnvironmentVariablessecretVolumesmaxInstanceRequestConcurrencyavailableCpubinaryAuthorizationPolicy)4serviceConfigr   r   r   r&   r   GetMapFlagsFromArgsApplyMapFlagssecrets_utilGetSecretsAsDictr   r   r   IsArgsSpecified
ApplyFlagsapi_util
GetProjectprojects_utilGetProjectNumberr   core_exceptionsreraiser   rA   SplitSecretsDict_GetVpcAndVpcEgressSettings_GetIngressSettingsgetattrset!serve_all_traffic_latest_revisionaddmemorymax_instancesclear_max_instancesmin_instancesclear_min_instancesrun_service_accountservice_accounttimeoutIsKnownAndSpecifiedr   r   unionServiceConfig_ParseMemoryStrToK8sMemoryEnvironmentVariablesValuesorteditemsAdditionalPropertySecretEnvVarsToMessagesSecretVolumesToMessages_ValidateK8sCpuStr)r]   r4   r~   old_env_varsadditional_propertyenv_var_flagsenv_varsold_secretsnew_secretserrorold_secret_env_varsold_secret_volumessecret_env_varssecret_volumesvpc_connectorvpc_egress_settingsvpc_updated_fieldsingress_settingsingress_updated_fieldsr   r   updated_fieldsbinary_authorization_policyservice_updated_fieldsr&   r   s                             rF   _GetServiceConfigr   E  s   & ,

)
)

)
)
>
>

)
)
>
>
S
S
 	''<<QQ 	 /B.G.Gl&**+ 	R ..z4@-##LBMB(++,:://''BB''55K
 ##D)@"--







(
()<)<)>
?	k K,:,K,K-)) %3$C$CK$P!/> "$2CD 9-$&8 .Ax-P**mT2+eT"#5.	++FG	[[89HI_56	#t'?'?:;	#t'?'?:;	)T-A-A-M=>	\\78=>++DE))67 $	:;CD 67"&";";CD$??0.
 4T[[A%%  !!%%  !!"66N$:N:N*$%844<'55OO
 %+8>>+;$<	$ %=jc5 ((BBUUU V  %=	$  P   &2%I%Ix& %<<h )4)#.$?A  !D G$
 $q  @j77>??@T$s   AR2 91S1 2	S.;(S))S.r   c                    | | syt        j                  t        | t         j                        }|s%t	        j
                  ddj                  |             |j                  d      }|j                  d      }|d}t        t        D cg c]  }|j                         |f c}      }|j                  |j                               }|s%t	        j
                  ddj                  |             ||z   }|S c c}w )a`  Parses user provided memory to kubernetes expected format.

  Ensure --gen2 continues to parse Gen1 --memory passed in arguments. Defaults
  as M if no unit was specified.

  k8s format:
  https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery/pkg/api/resource/generated.proto

  Args:
    memory: input from `args.memory`

  Returns:
    k8s_memory: str|None, in kubernetes memory format. GCF 2nd Gen control plane
      is case-sensitive and only accepts: value + m, k, M, G, T, Ki, Mi, Gi, Ti.

  Raises:
    InvalidArgumentException: User provided invalid input for flag.
  Nz--memoryz'Invalid memory value for: {} specified.suffixamountr+   !Invalid suffix for: {} specified.)rer@   _MEMORY_VALUE_PATTERNVERBOSEr   InvalidArgumentExceptionformatrE   dict_GCF_GEN2_UNITSupperget)r   r@   r   r   unituppercased_gen2_unitscorrected_suffixparsed_memorys           rF   r   r     s    & ^6
(((&"**
=%	

-
-=DDVL  ;;x &;;x & ^F (78

d8 +..v||~>	

-
-7>>vF  ++-	 9s   	C6r   c                    | yt        j                  t        | t         j                        }|s%t	        j
                  ddj                  |             |j                  d      xs d}|j                  d      }|r|dk(  r%t	        j
                  ddj                  |             |r-|t        vr%t	        j
                  dd	j                  |             ||z   }|S )
ax  Validates user provided cpu to kubernetes expected format.

  k8s format:
  https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery/pkg/api/resource/generated.proto

  Args:
    cpu: input from `args.cpu`

  Returns:
    k8s_cpu: str|None, in kubernetes cpu format.

  Raises:
    InvalidArgumentException: User provided invalid input for flag.
  Nz--cpuz$Invalid cpu value for: {} specified.r    r   r   z!Invalid amount for: {} specified.r   )	r   r@   _CPU_VALUE_PATTERNr   r   r   r   rE   _GCF_GEN2_CPU_UNITS)r   r@   r   r   r   s        rF   r   r   
  s     	[
((%sBJJ
7%	

-
-7>>sC  ;;x &B&;;x &	6S=

-
-4;;C@  11

-
-4;;C@  6/-	rH   c                    | j                   rdt        |rdgng       }}n| j                  s| j                  rt	        | |      t        dg      }}nn| j
                  s| j                  s| j                  rt        | |      t        dg      }}n1|r|j                  t               }}nt        j                  g dd      | j                  d      r(t        | ||      \  }}||_        |j                  |      }|r3t!        j"                  |j$                        rt'        j(                          |r>t!        j*                  |j$                        rt'        j,                  |j.                         ||fS )a  Constructs an EventTrigger message from the command-line arguments.

  Args:
    args: The arguments that this command was invoked with.
    messages: messages module, the GCFv2 message stubs.
    existing_function: The pre-existing function.

  Returns:
    A tuple `(event_trigger, update_fields_set)` where:
    - `event_trigger` is a `cloudfunctions_v2_messages.EventTrigger` used to
    request events sent from another service,
    - `updated_fields_set` is a set of update mask fields.
  Nevent_trigger)z--trigger-topicz--trigger-bucketz--trigger-http--trigger-eventz--trigger-event-filtersz9You must specify a trigger when deploying a new function.r!   )trigger_httpr   trigger_eventtrigger_resource_GetEventTriggerForEventTypetrigger_topictrigger_buckettrigger_event_filters_GetEventTriggerForOthereventTriggercalliope_exceptionsOneOfArgumentsRequiredExceptionIsSpecified	_GetRetryretryPolicyr   trigger_typesIsPubsubType	eventTyper   'ensure_pubsub_sa_has_token_creator_roleIsAuditLogType#ensure_data_access_logs_are_enabledeventFilters)r]   r4   r~   r   updated_fields_setretry_policyretry_updated_fields          rF   _GetEventTriggerr  3  sb   $ 
(,i.B/%M T22(Dh)/"# &M T00D4N4N(@h)/"# &M
 

(
(
+ (m
  ?? F	 	 
g(1$-(P%L% ,M+112EF}11-2I2IJ779}33M4K4KL33M4N4NO	*	**rH   c                    | j                   }| j                  }| j                  xs | j                  }|t        j
                  v rKt        j                  |      }|j                  t        j                  t        |      || j                        S |t        j                  v s|t        j                  v rzt        j                  j!                  |      j"                  }t        j                  j%                  ||      }|j                  ||j'                  d|      g|| j                        S t)        j*                  ddj-                  |            )a8  Constructs an EventTrigger message from the command-line arguments.

  Args:
    args: The arguments that this command was invoked with.
    messages: messages module, the GCFv2 message stubs.

  Returns:
    A `cloudfunctions_v2_messages.EventTrigger`, used to request
      events sent from another service.
  )r  pubsubTopicr   triggerRegionr;   	attributer   )r  r  r   r  r   zOEvent type {} is not supported by this flag, try using --trigger-event-filters.)r   r   trigger_service_accountr   r   PUBSUB_MESSAGE_PUBLISH_TYPESapi_util_v1ValidatePubsubTopicNameOrRaiseEventTriggerEA_PUBSUB_MESSAGE_PUBLISHED_BuildFullPubsubTopictrigger_locationEVENTARC_STORAGE_TYPES!EVENTFLOW_TO_EVENTARC_STORAGE_MAPr   BucketReferenceFromUrlr;   r   EventFilterr   r   r   )r]   r4   r   r   service_account_emailpubsub_topicbucket_namestorage_event_types           rF   r   r   r  sI    $$-**66N$:N:Nh;;;==>NOL  66),71++	 !   x666	(DD	D ..667GHOOK!CCGG}   $  8; G
 2++ !   
-
-	$$*F=$9 rH   c                    g }d}d}| j                   xs | j                  }| j                  }| j                  r't        j
                  }t        | j                        }n| j                  rC| j                  dd j                  d      }t        j                  }|j                  d|      g}n| j                  r| j                  j                  d      }| j                  j                         D 	cg c]  \  }}	|dk7  r|j                  ||	       }}}	| j                  rPd}
|j                  | j                  j                         D 	cg c]  \  }}	|j                  ||	|
       c}	}       d}| j                   r2| j"                  j                   j%                         j'                         }|j)                  ||||||	      S c c}	}w c c}	}w )
a9  Constructs an EventTrigger when using `--trigger-[bucket|topic|filters]`.

  Args:
    args: arguments that this command was invoked with.
    messages: messages module, the GCFv2 message stubs.

  Returns:
    A `cloudfunctions_v2_messages.EventTrigger` used to request
      events sent from another service.
  N   /r;   r  typezmatch-path-pattern)r  r   operator)r  r  r  r   channelr  )r  r   r  r   r   r  r  r   rstripEA_STORAGE_FINALIZEr  r   r   r   "trigger_event_filters_path_patternextendtrigger_channelCONCEPTSParserq   r  )r]   r4   event_filters
event_typer   r  r  r;   attrvalr'  r-  s               rF   r   r     s    -*,66N$:N:N**	55J(););<L  $++C0F--J))HF)KLM!!++//7J 3399;;ID#6> 	t37;  
 ..%hBBHHJJidC 

S8

LJ 	
 /	mm3399;HHJO			 /$ 
 
 !s   3"GG
r   c                     |t        j                  t              | j                  r'|j                  j                  d      t        dg      fS |j                  j                  d      t        dg      fS )a  Constructs an RetryPolicy enum from --(no-)retry flag.

  Args:
    args: arguments that this command was invoked with.
    messages: messages module, the GCFv2 message stubs.
    event_trigger: trigger used to request events sent from another service.

  Returns:
    A tuple `(retry_policy, update_fields_set)` where:
    - `retry_policy` is the retry policy enum value,
    - `update_fields_set` is the set of update mask fields.
  RETRY_POLICY_RETRYzeventTrigger.retryPolicyRETRY_POLICY_DO_NOT_RETRY)r   rA   !_INVALID_RETRY_FLAG_ERROR_MESSAGEr!   r  RetryPolicyValueValuesEnumr   )r]   r4   r   s      rF   r   r     s    $ 

#
#$E
FF	ZZ  ;;,-./ /
   ;;#,-./ /rH   r   c                 J    dj                  t        j                         |       S )Nzprojects/{}/topics/{})r   r   r   )r   s    rF   r  r    s    	 	'	'(;(;(=|	LLrH   c                 \   t        | |||      \  }}i }|r|j                  rt|j                  j                  r^|j                  j                  j                  r>|j                  j                  j                  D ]  }|j                  ||j
                  <    t        j                  d|       }t        j                  |fi |}	t               }
|	|k7  r|
j                  d       | j                  |
j                  d       | j                  |
j                  d       | j                  rdn| j                  }| j                  | j                  r|
j                  d       | j                  }|| j                   r|
j                  d       |j"                  }d}d}| j%                  d      rO|
j'                  d	       | j(                  d
k(  r|j+                         }| j(                  dk(  r|j-                         }t.        j1                  ||
      }|j3                  | j                  | j                  |||j2                  j5                  t7        |	j9                               D cg c],  \  }}|j2                  j4                  j;                  ||      . c}}      |||      |fS c c}}w )aa  Constructs a BuildConfig message from the command-line arguments.

  Args:
    args: arguments that this command was invoked with.
    client: The GCFv2 API client.
    function_ref: The GCFv2 functions resource reference.
    existing_function: The pre-existing function.

  Returns:
    The resulting build config and the set of update mask fields.
  zbuild-env-varsz"build_config.environment_variablesNzbuild_config.entry_pointzbuild_config.runtimezbuild_config.worker_poolzbuild_config.service_accountruntime_update_policy)z$build_config.automatic_update_policyz$build_config.on_deploy_update_policy	automaticz	on-deployr   r   )
entryPointr   r5   
workerPoolr   serviceAccountautomaticUpdatePolicyonDeployUpdatePolicy)r   r   r   r   r   r&   r   r   r   r   r   entry_pointr   clear_build_worker_poolbuild_worker_poolbuild_service_accountclear_build_service_accountrd   r   updater;  AutomaticUpdatePolicyOnDeployUpdatePolicyr   r   BuildConfigr   r   r   r   )r]   r   r^   r~   function_sourcesource_updated_fieldsold_build_env_varsr   build_env_var_flagsbuild_env_varsr   worker_poolr   r4   automatic_update_policyon_deploy_update_policybuild_updated_fieldsr&   r   s                      rF   _GetBuildConfigrT     s   " ,6
	,(/( 

'
'

'
'
<
<

'
'
<
<
Q
Q
 	%%::OO 	 5H4M4M,001 	P !445EtL))/. 5.));<	!12	\\-.44$:P:P+	'4+G+G12../ D$D$D56##(  	-.   !![0 ( > > @!![0 ( = = ?")>O%%,,  '33MM
 %+>+?+?+A$B	$ %Cjc5 &&@@SSU T  %C	$  N   ) 76  " %
 $s   $1J(c                     | j                  d      r| j                  S | j                  d      ry|sdS |j                  S )zRetrives KMS key applicable to the deployment request.

  Args:
    args: arguments that this command was invoked with.
    existing_function: the pre-existing function.

  Returns:
    Either newly passed or pre-existing KMS key.
  r_   clear_kms_keyN)r   r_   ra   )r]   r~   s     rF   r   r   c  sA     
i <<(&H,=,H,HHrH   c                     | j                   rat        j                  d|j                  j                  t
        j                        j                  | j                         }|t        dg      fS dt               fS )a  Constructs ingress setting enum from command-line arguments.

  Args:
    args: arguments that this command was invoked with.
    messages: messages module, the GCFv2 message stubs.

  Returns:
    A tuple `(ingress_settings_enum, updated_fields_set)` where:
    - `ingress_settings_enum` is the ingress setting enum value,
    - `updated_fields_set` is the set of update mask fields.
  r   arg_namemessage_enumcustom_mappingszservice_config.ingress_settingsN)	r   r   ChoiceEnumMapperr   IngressSettingsValueValuesEnumr   INGRESS_SETTINGS_MAPPINGGetEnumForChoicer   )r]   r4   ingress_settings_enums      rF   r   r   w  sq     
%66#++JJ66 t,,-	 
 !)-N,O"PPPrH   c                    | j                   rddt        ddg      fS t               }d}| j                  rD| j                  j                  j                         j                         }|j                  d       n:|r8|j                  r,|j                  j                  r|j                  j                  }d}| j                  r||st        j                  dd      t        j                  d|j                  j                   t"        j$                        j'                  | j                        }|j                  d       ||t        |      fS )a  Constructs vpc connector and egress settings from command-line arguments.

  Args:
    args: The arguments that this command was invoked with.
    messages: messages module, the GCFv2 message stubs.
    existing_function: The pre-existing function.

  Returns:
    A tuple `(vpc_connector, egress_settings, updated_fields_set)` where:
    - `vpc_connector` is the name of the vpc connector,
    - `egress_settings` is the egress settings for the vpc connector,
    - `updated_fields_set` is the set of update mask fields.
  Nzservice_config.vpc_connectorz,service_config.vpc_connector_egress_settingszvpc-connectorzCFlag `--vpc-connector` is required for setting `--egress-settings`.egress_settingsrX  )clear_vpc_connectorr   r   r   r.  r/  rq   r   r   r   rb  r   RequiredArgumentExceptionr   r\  r   )VpcConnectorEgressSettingsValueValuesEnumr   EGRESS_SETTINGS_MAPPINGr_  )r]   r4   r~   update_fields_setr   rb  s         rF   r   r     s5   , 
*:
 	  e-	MM//557DDFM89

)
)

)
)
6
6%33@@M/	00

O 
  00"++UU55 t++,	 
 HI	3D)E	EErH   c                 z    t         D ]2  \  }}| j                  |      st        j                  t        |z         y)zDEnsures that only the arguments supported in V2 are passing through.N)_V1_ONLY_FLAGSr   r   rA   _V1_ONLY_FLAG_ERROR)r]   flag_variable	flag_names      rF   _ValidateV1OnlyFlagsrm    s6    "0mY.%%&9I&EFF #1rH   c                 .   |ri }nt         t        i}t        j                  j	                  | |      }|j                  |j                  j                  |r|j                  nd      }|j                  r|j                  t        dg      fS dt               fS )a  Constructs labels from command-line arguments.

  Args:
    args: The arguments that this command was invoked with
    messages: messages module, the GCFv2 message stubs.
    existing_function: The pre-existing function.

  Returns:
    A tuple `(labels, updated_fields_set)` where:
    - `labels` is functions labels metadata,
    - `updated_fields_set` is the set of update mask fields.
  )required_labelsNlabels)_DEPLOYMENT_TOOL_LABEL_DEPLOYMENT_TOOL_VALUEr   DiffFromUpdateArgsApplyFunctionLabelsValuerp  needs_updater   )r]   r4   r~   ro  labels_difflabels_updates         rF   
_GetLabelsr{    s    " O-/EFO  //
O 0 + ####"3- H:!666rH   functionc                    t               }|r|j                  nd|_        | j                  d      s| j                  d      r$| j                  d      rdn| j                  |_        ||j                  |j                  k7  r=| j                   t	        j
                  |j                  |       |j                  d       |S )a  Sets CMEK-related fields on the function.

  Args:
    args: arguments that this command was invoked with.
    function: `cloudfunctions_v2alpha_messages.Function`, the recently created
      or updated GCF function.
    existing_function: `cloudfunctions_v2_messages.Function | None`, the
      pre-existing function.
    function_ref: resource reference.

  Returns:
    A set of update mask fields.
  Nr_   rV  kms_key_name)r   ra   r   r_   r	   ValidateKMSKeyForFunctionr   )r]   r|  r~   r^   r   s        rF   _SetCmekFieldsr    s    & 5.&7""T  
i D$4$4_$E  1t||  			 1 < <	<||))(*=*=|L~&	rH   c                 &   t               }|r|j                  j                  nd|j                  _        | j                  d      s| j                  d      r| j                  d      rdn| j                  }t        j                  |      |j                  _        |-|j                  j                  |j                  j                  k7  r|j                  d       |j                  r,|j                  j                  st        j                  dd      |S )ar  Sets user-provided docker repository field on the function.

  Args:
    args: arguments that this command was invoked with
    function: `cloudfunctions_v2_messages.Function`, recently created or updated
      GCF function.
    existing_function: `cloudfunctions_v2_messages.Function | None`,
      pre-existing function.

  Returns:
    A set of update mask fields.
  Ndocker_repositoryclear_docker_repositoryzbuild_config.docker_repositoryz--docker-repositoryzTA Docker repository must be specified when a KMS key is configured for the function.)r   r   dockerRepositoryr   r  r	   NormalizeDockerRepositoryFormatr   ra   r   rd  )r]   r|  r~   r   updated_docker_repositorys        rF   _SetDockerRepositoryConfigr    s   " 5. 
 ##44 '
 
)*d.>.>/
 56 	##  	112KL ) 	!00((99: 9:!5!5!F!F

7
7!  
rH   rk   c                 N    t        j                  dj                  |       d      S )zMPrompts the user to allow unauthenticated invocations for the given function.z7Allow unauthenticated invocations of new function [{}]?F)prompt_stringdefault)r   PromptContinuer   )rk   s    rF   (_PromptToAllowUnauthenticatedInvocationsr  P  s&    		"	"
C
J
J4
P	
 rH   
gcf_clientc                 $   | j                   }| j                  }|j                  |j                         j	                         |j                         |      }|j                  j                  |      }d}t        j                  ||||t               y)a  Create a function.

  This does not include setting the invoker permissions.

  Args:
    gcf_client: The GCFv2 API client.
    function_ref: The GCFv2 functions resource reference.
    function: `cloudfunctions_v2_messages.Function`, The function to create.

  Returns:
    None
  )rc   
functionIdr|  zDeploying functionN)r   r4   5CloudfunctionsProjectsLocationsFunctionsCreateRequestrp   rq   Namerm   Creater   WaitForOperation_EXTRA_STAGES)r  r^   r|  r   r4   create_request	operationoperation_descriptions           rF   _CreateAndWaitr  Z  s    " &  (DD$$&335!&&( E   1188H).
h	#8-rH   r	  c                 `   | j                   }| j                  }|ru|j                  |j                         dj	                  t        |            |      }|j                  j                  |      }d}t        j                  ||||t               yt        j                  j                  d       y)aO  Update a function.

  This does not include setting the invoker permissions.

  Args:
    gcf_client: The GCFv2 API client.
    function_ref: The GCFv2 functions resource reference.
    function: `cloudfunctions_v2_messages.Function`, The function to update.
    updated_fields_set: A set of update mask fields.

  Returns:
    None
  ,)rk   
updateMaskr|  z$Updating function (may take a while)zNothing to update.N)r   r4   4CloudfunctionsProjectsLocationsFunctionsPatchRequestrq   joinr   rm   Patchr   r  r  r   statusPrint)	r  r^   r|  r	  r   r4   update_requestr  r  s	            rF   _UpdateAndWaitr  |  s    & &  (EE**,xx'9 :; 	F 	
  3399.IIB)%:M JJ)*rH      i  )max_retrialssleep_msc                     	 | j                  |j                               S # t        j                  $ r}t	        j
                  d|      d}~ww xY w)z Retrieves a function with retry.z"Function not found after retries, N)GetFunctionrq   rr   rs   r   rA   )r   r^   r   s      rF   _GetFunctionWithRetryr    sN    Ql779::		&	& Q

#
#$H%
PPQs   ! AA

Arelease_trackc           	      4	   t        j                  |      }|j                  }| j                  j                  j                         }t        |        |j                  |j                               }|j                  |j                        j                  D ci c]3  }t        |j                        dk(  r|j                  d|j                  i5 }}|du }|r| j                  st!        j"                         st%        j&                  dd      t)        |j+                               }	t!        j,                  |	d      }
|	|
   | _        t.        j0                  j3                  d	j5                  | j                               t7        j8                         r0|r.t        |j                        d
k(  rt;        j<                  dd      | j                  xs |j>                  j                  }|r||vrt;        j<                  d| d      ||v r*||   d   r"||   d   D ]  }t/        j@                  |        |r?|jB                  r3|jB                  jD                  }||st/        j@                  tF               tI        | ||      \  }}tK        | |jL                  ||      \  }}tO        | ||      \  }}tQ        | ||      \  }}|jS                  |j                         ||||      }tU        | |||      }tW        | ||      }tY        jZ                  d       tY        jZ                  d       tY        jZ                  d       d}| j]                  d      r| j^                  }n|r|sta        | jb                        }te        jf                  ti        jj                         |j                  |jl                         |rto        |||       n(tp        js                  ||||||      }tu        ||||       tw        ||      }|r|s|r7| j]                  d      r&ty        jz                  ||t|        j~                         t.        j0                  j3                  ddj5                  |j                  |j                         ti        jj                               z          |S c c}w )z/Runs a function deployment with the given args.)r  GEN_2warningsNr   z/Flag `--runtime` is required for new functions.zPlease select a runtime:
)messagezCTo skip this prompt, add `--runtime={}` to your command next time.
GEN_1z--gen2zAFunction already exists in 1st gen, can't change the environment.z	--runtimezt is not a supported runtime on GCF 2nd gen. Use `gcloud functions runtimes list` to get a list of available runtimes)rk   r   r   r   rp  zrun.googleapis.comzcloudbuild.googleapis.comzartifactregistry.googleapis.comallow_unauthenticated)add_bindingmemberz6You can view your function in the Cloud Console here: zDhttps://console.cloud.google.com/functions/details/{}/{}?project={}
)A	client_v2FunctionsClientr4   r.  rk   r/  rm  r  rq   ListRuntimeslocationsIdruntimesstrenvironmentr  r   r   	CanPromptr   rd  r   keysPromptChoicer   r  r  r   r   ShouldUseGen2r   r   r   warningr   r   (_LATEST_REVISION_TRAFFIC_WARNING_MESSAGEr  rT  r   r   r{  rv  r  r  r   PromptToEnableApiIfDisabledr   r  r  NAMEr   2ValidateDefaultBuildServiceAccountAndPromptWarningr   r   r?  r  r   r   r  r  r   AddOrRemoveInvokerBindingr   "ALLOW_UNAUTH_POLICY_BINDING_MEMBERr  )r]   r  r   r4   r^   r~   rgen2_runtimesis_new_functionr  idxr   w"has_all_traffic_on_latest_revisionr   trigger_updated_fieldsbuild_configrS  service_configr   labels_valuelabels_updated_fieldsr|  cmek_updated_fields docker_repository_updated_fieldsr  r   s                              rF   Runr    sv    $$=A&__(##))+,t(()B)B)DE ""<#;#;<EEE!	Q]]	w	& ffz1::&&E   &-/T\\!99
F  m((*+H

!
!6C C=DLJJN		 

++
,
7

-
-K  LLA-99AA'-

-
-i ) )  -"8"D7#J/	kk!n 0 ,::''BB ' 	+62	kk:;*:
H'+'-' (7
mm	($,$ ,=
H',(.( )3
H')%,%
 $$& "  ( '
H' &@
H'&" ,,-AB,,-HI,,-NO	-. 66}DTYYOII!!
 6<2__(N 6<>B"6<8(
 
 



2
3&&)$GG **>Ov

"
"L$5$5$79L9L9N 
/as   8R)N)__doc__r   r   typingr   r   r   apitools.base.pyr   r   rr    googlecloudsdk.api_lib.functionsr   r	   r
   r   #googlecloudsdk.api_lib.functions.v1r   r  #googlecloudsdk.api_lib.functions.v2r   r  	api_typesr   googlecloudsdk.api_lib.storager   googlecloudsdk.callioper   calliope_baser   r   #googlecloudsdk.calliope.arg_parsersr   #googlecloudsdk.command_lib.eventarcr  $googlecloudsdk.command_lib.functionsr   r   r   r   r   r   'googlecloudsdk.command_lib.functions.v2r   #googlecloudsdk.command_lib.projectsr   googlecloudsdk.command_lib.runr   $googlecloudsdk.command_lib.util.apisr   $googlecloudsdk.command_lib.util.argsr   googlecloudsdk.corer   r   r   googlecloudsdk.core.consoler   r   googlecloudsdk.core.utilr    re   r!   !_SIGNED_URL_UPLOAD_ERROR_MESSSAGEcompiler?   rB   rU   rV   r7  r  ri  rj  rq  rr  Stage_ARTIFACT_REGISTRY_STAGE_SERVICE_ROLLBACK_STAGE_TRIGGER_ROLLBACK_STAGEr  r   r   r   r   
ModuleTyper  rC   rG   r\   	NamespaceBaseApiClientResourcer}   rv  r   r   r   r   r   r  r  r   r   RetryPolicyr   r  r  rJ  rT  r   IngressSettingsr   VpcConnectorEgressSettingsr   rm  rw  r{  r  r  boolr  r  r  RetryOnExceptionr  ReleaseTrackr   rH   rF   <module>r     s   O 
  - - % > ; 6 D C C : B @ 7 9 E 5 A F 6 < 9 ? E < ? E @ : 9 = # ) 2 8 8 * "
 BJJ23   BJJ	 Q  K "
. ) D  + %  2+111  1*00+  1*00, 
  eo-   E,, c i>N>N *"1E,, "1c "1i>N>N "1T "3?

%
%3?""3? $$3? 	3?
 c]3? 3?l.*

%
%.*"".* $$.*  	 2 23	.*
 8I$$%y~56.*bP

%
%PP  	 2 23P 9""IcN23	Pf/s /x} /d&C &HSM &R<+

%
%<+<+  	 2 23<+ 8I**+Ys^;<	<+~1

%
%1161A1A11h3

%
%3161A1A33l/

%
%// I223/ 9  )C.01	/@M M M`

%
%`%%` $$`  	 2 23	`
 9  )C.01`FI

%
%I	 2 23I c]I(

%
%161A1A
8I--.	#>?2<F

%
%<F<F SMY112cN	<F~G0:: Gt G

%
%  	 2 23 8I))*IcN:;	D"

%
%"  "  	 2 23" $$	"
 s^"J0

%
%0  0  	 2 230 s^	0f3 4 ))$$    
	D%+))%+$$%+   %+ "#	%+
 
%+P Q6Q 7Q]

%
%]6C6P6P]]rH   