
                            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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%Z%ddl&m'Z' ddl&m(Z( e jR                  jT                  de jR                  jV                  de jR                  jX                  diZ-d Z.dgZ/ G d d ej`                        Z1y)!zDFunctions for creating a client to talk to the App Engine Admin API.    )absolute_import)division)unicode_literalsN)encoding)
exceptions)
list_pager)build)env)instances_util)operations_util)region_util)service_util)util)version_util)appengine_api_client_base)logs)convert_yaml)base)log)
properties)	resources)filter)mapv1v1alphav1betac                 >    t         |    }t        j                  |      S N)APPENGINE_VERSIONS_MAPAppengineApiClientGetApiClient)release_trackapi_versions     6lib/googlecloudsdk/api_lib/app/appengine_api_client.pyGetApiClientForTrackr%   9   s    &}5+		(	(	55    python27c                      e Zd ZdZd Zd Zd Zd%dZd&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 Zd)dZd%dZd Zd Zd(dZd(dZd Zd Zd Zd Zd Zd Zd%dZ	 	 d&dZ d  Z!d! Z"d" Z#d# Z$d$ Z%y)*r    z=Client used by gcloud to communicate with the App Engine API.c                     | j                   j                  | j                               }| j                  j                  j                  |      S )zRetrieves the application resource.

    Returns:
      An app resource representing the project's app.

    Raises:
      apitools_exceptions.HttpNotFoundError if app doesn't exist
    name)messagesAppengineAppsGetRequest
_FormatAppclientappsGet)selfrequests     r$   GetApplicationz!AppengineApiClient.GetApplicationC   s=     mm339J3KG;;((r&   c                     | j                   j                  | j                         |      }| j                  j                  j                  |      S )aG  Lists the available runtimes for the given App Engine environment.

    Args:
      environment: The environment for the application, either Standard or
        Flexible.

    Returns:
      v1beta|v1.ListRuntimesResponse, the list of Runtimes.

    Raises:
      apitools_exceptions.HttpNotFoundError if app doesn't exist
    )parentenvironment)r,    AppengineAppsListRuntimesRequestr.   r/   r0   ListRuntimes)r2   r7   r3   s      r$   r9   zAppengineApiClient.ListRuntimesO   sF     mm<< k = G ;;((11r&   c                     |j                   | j                  j                  j                  j                  | j                  j                  j                  j
                  fv }|S )a  Checks application resource to get serving status.

    Args:
      app: appengine_v1_messages.Application, the application to check.

    Returns:
      bool, whether the application is currently disabled. If serving or not
        set, returns False.
    )servingStatusr,   ApplicationServingStatusValueValuesEnumUSER_DISABLEDSYSTEM_DISABLED)r2   appstoppeds      r$   	IsStoppedzAppengineApiClient.IsStoppeda   sT     !!>>LL!!>>NN$P PG Nr&   Nc                    | j                   j                  | j                         | j                   j                               }| j                  j
                  j                  |      }t        j                  dj                  |j                               t        j                  | j                  j                  ||      S )a  Creates missing app resources.

    In particular, the Application.code_bucket GCS reference.

    Args:
      progress_message: str, the message to use while the operation is polled,
        if not the default.

    Returns:
      A long running operation.
    )r+   repairApplicationRequest!Received operation: [{operation}]	operationmessage)r,   AppengineAppsRepairRequestr.   RepairApplicationRequestr/   r0   Repairr   debugformatr+   r   WaitForOperationapps_operations)r2   progress_messager3   rG   s       r$   RepairApplicationz$AppengineApiClient.RepairApplicationp   s     mm66__!%!G!G!I 7 KG   ''0III188.. 9 " # ++##Y8HJ Jr&   c                    d}|r)| j                   j                  | j                  ||      }n'| j                   j                  | j                  |      }|r||_        | j                  j
                  j                  |      }t        j                  dj                  |j                               dj                  | j                  |      }t        j                  | j                  j                  ||      S )	a|  Creates an App Engine app within the current cloud project.

    Creates a new singleton app within the currently selected Cloud Project.
    The action is one-time and irreversible.

    Args:
      location: str, The location (region) of the app, i.e. "us-central"
      service_account: str, The app level service account of the app, i.e.
        "123@test-app.iam.gserviceaccount.com"
      ssl_policy: enum, the app-level SSL policy to update for this App Engine
        app. Can be DEFAULT or MODERN.

    Raises:
      apitools_exceptions.HttpConflictError if app already exists

    Returns:
      A long running operation.
    N)id
locationIdserviceAccount)rT   rU   rE   rF   zMCreating App Engine application in project [{project}] and region [{region}].)projectregionrH   )r,   r<   rW   	sslPolicyr/   r0   Creater   rM   rN   r+   r   rO   rP   )r2   locationservice_account
ssl_policycreate_requestrG   rI   s          r$   	CreateAppzAppengineApiClient.CreateApp   s    & N}}00\\h 1 Pn }}00\\h 1 0n !+n  ''7III188.. 9 " #$$*F4<<2: %+ %<  ++DKK,G,G,5wH Hr&   c           	         | j                  |||||||      }dj                  |      }	|j                  t        j                  t        j                  fv r|	dz  }	| j                         }
|r|j                         r|
st        j                  d       nt        j                  | j                  j                  |
      }t        j                  | j                  j                  ||	|      }t        j                  ||
      }|rt        j                   j#                  |      }|r|j%                         r	 t&        j(                  j+                  |j,                  dt.        j0                  j2                  j4                  j6                  id      }t9        j:                         j=                  |t        j>                  	       t        jN                  | j                  j                  |
      }t        j                  | j                  j                  ||	|      S # t@        jB                  $ r tE        jF                  | jI                         jJ                        }t&        j(                  jM                  d
t.        j0                  j2                  j4                  j6                  ||j,                        }t9        j:                         j=                  |t        j>                  	       Y &w xY w)a  Updates and deploys new app versions.

    Args:
      service_name: str, The service to deploy.
      version_id: str, The version of the service to deploy.
      service_config: AppInfoExternal, Service info parsed from a service yaml
        file.
      manifest: Dictionary mapping source files to Google Cloud Storage
        locations.
      build: BuildArtifact, a wrapper which contains either the build
        ID for an in-progress parallel build, the name of the container image
        for a serial build, or the options for creating a build elsewhere. Not
        present during standard deploys.
      extra_config_settings: dict, client config settings to pass to the server
        as beta settings.
      service_account_email: Identity of this deployed version. If not set, the
        Admin API will fall back to use the App Engine default appspot service
        account.

    Returns:
      The Admin API Operation, unfinished.

    Raises:
      apitools_exceptions.HttpNotFoundError if build ID doesn't exist
    zUpdating service [{service}]servicez  (this may take several minutes)zIUnable to determine build from Operation metadata. Skipping log streaming)rI   poller	projectIdzcloudbuild.projects.builds)params
collection)outz$cloudbuild.projects.locations.builds)rf   
projectsIdlocationsIdbuildsId)(_CreateVersionrN   r
   FLEXMANAGED_VMS_ResolveMetadataTypeIsBuildOptionsr   warningr   AppEngineOperationBuildPollerr/   rP   rO   GetBuildFromOperationapp_cloud_buildBuildArtifactMakeBuildIdArtifact	IsBuildIdr   REGISTRYParse
identifierr   VALUEScorerW   	GetOrFailcloudbuild_logsCloudBuildClientStreamstatusapitools_exceptionsHttpNotFoundErrorr   ConvertToCloudRegionr4   rU   rZ   AppEngineOperationPoller)r2   service_name
version_idservice_configmanifestr	   extra_config_settingsservice_account_emailrG   rI   operation_metadata_typerc   build_id	build_refrX   done_pollers                   r$   DeployServicez AppengineApiClient.DeployService   so   B ##L*n$,e5J$9;I -33L3IGchh8833g"779%%'$ - 	. !>>KK'')@B#44KK''G	 #88.0!//CCHM%"M&&,,!2!2!7!7!?!?!I!IJ3 - 5	 	((*11)1L "::##%<>K++##	  !22 M**4+>+>+@+K+KL&&--=!((--55??%%	 . '	
 	((*11)1LMs   6BH CK*)K*c                 |    d| j                   j                  j                         z   }t        | j                  |      S )zAAttempts to resolve the expected type for the operation metadata.OperationMetadata)r/   _VERSIONtitlegetattrr,   )r2   metadata_type_names     r$   rn   z'AppengineApiClient._ResolveMetadataType  s4     -t{{/C/C/I/I/KK4=="455r&   c                     | j                  ||||||      }| j                  j                  | j                  |      |      }	| j                  j
                  j                  |	      S )a  Begins the updates and deployment of new app versions.

    Args:
      service_name: str, The service to deploy.
      version_id: str, The version of the service to deploy.
      service_config: AppInfoExternal, Service info parsed from a service yaml
        file.
      manifest: Dictionary mapping source files to Google Cloud Storage
        locations.
      build: BuildArtifact, a wrapper which contains either the build ID for an
        in-progress parallel build, the name of the container image for a serial
        build, or the options to pass to Appengine for a server-side build.
      extra_config_settings: dict, client config settings to pass to the server
        as beta settings.
      service_account_email: Identity of this deployed version. If not set, the
        Admin API will fall back to use the App Engine default appspot service
        account.

    Returns:
      The Admin API Operation, unfinished.
    r   )r6   version)_CreateVersionResourcer,   *AppengineAppsServicesVersionsCreateRequest_GetServiceRelativeNamer/   apps_services_versionsrZ   )
r2   r   r   r   r   r	   r   r   version_resourcer^   s
             r$   rk   z!AppengineApiClient._CreateVersion  sr    : 22>83=u3H3HJ ]]MM+++F  N "N ;;--44^DDr&   c                     | j                   j                  | j                  |            }| j                  j                  j                  |      S )zDescribe the given service.

    Args:
      service: str, the ID of the service

    Returns:
      Service resource object from the API
    r*   )r,   AppengineAppsServicesGetRequestr   r/   apps_servicesr1   )r2   rb   r3   s      r$   GetServiceResourcez%AppengineApiClient.GetServiceResource3  sF     mm;;))'2 < 4G;;$$((11r&   c                 .    |di}| j                  ||      S )zSets the default serving version of the given services.

    Args:
      service_name: str, The service name
      version_id: str, The version to set as default.
    Returns:
      Long running operation.
    g      ?)SetTrafficSplit)r2   r   r   allocationss       r$   SetDefaultVersionz$AppengineApiClient.SetDefaultVersion@  s!     s#Kk::r&   c                    t        j                  | j                  j                  ||d      }| j                  j	                  | j                  |      | j                  j                  |      |d      }dj                  |      }| j                  j                  j                  |      }t        j                  | j                  j                  ||      S )	aR  Sets the traffic split of the given services.

    Args:
      service_name: str, The service name
      allocations: A dict mapping version ID to traffic split.
      shard_by: A ShardByValuesEnum value specifying how to shard the traffic.
      migrate: Whether or not to migrate traffic.
    Returns:
      Long running operation.
    )r   shardByr   )splitr   )r+   rb   migrateTraffic
updateMaskz-Setting traffic split for service [{service}]ra   rH   )r   PyValueToMessager,   TrafficSplit!AppengineAppsServicesPatchRequestr   ServicerN   r/   r   Patchr   rO   rP   )	r2   r   r   shard_bymigratetraffic_splitupdate_service_requestrI   rG   s	            r$   r   z"AppengineApiClient.SetTrafficSplitN  s     --dmm.H.H>I:B/DEM "]]LL))|)D%%M%:	 M  >DD E G))//0FGI++DKK,G,G,54;= =r&   c                    | j                   j                  |      }| j                   j                  | j                  |      | j                   j	                  |      d      }dj                  |      }| j                  j                  j                  |      }t        j                  | j                  j                  ||      S )	a  Sets the ingress traffic allowed for a service.

    Args:
      service_name: str, The service name
      ingress_traffic_allowed: An IngressTrafficAllowed enum.

    Returns:
      The completed Operation. The Operation will contain a Service resource.
    )ingressTrafficAllowedr   )networkSettingsr   )r+   rb   r   z0Setting ingress settings for service [{service}]ra   rH   )r,   NetworkSettingsr   r   r   rN   r/   r   r   r   rO   rP   )r2   r   ingress_traffic_allowednetwork_settingsr   rI   rG   s          r$   SetIngressTrafficAllowedz+AppengineApiClient.SetIngressTrafficAllowedl  s     }}445 5 7!]]LL))|)D%%6F%G$ M &
 AGG H G))//0FGI++##YA Ar&   c                 "   | j                   j                  | j                  ||            }| j                  j                  j                  |      }dj                  ||      }t        j                  | j                  j                  ||      S )zDeletes the specified version of the given service.

    Args:
      service_name: str, The service name
      version_id: str, The version to delete.

    Returns:
      The completed Operation.
    r   r   r*   zDeleting [{0}/{1}]rH   )
r,   *AppengineAppsServicesVersionsDeleteRequest_FormatVersionr/   r   DeleterN   r   rO   rP   )r2   r   r   delete_requestrG   rI   s         r$   DeleteVersionz AppengineApiClient.DeleteVersion  s     ]]MM  l,6 ! 8 N 9N 2299.II")),
CG++##YA Ar&   c                 :   | j                   j                  | j                  ||      | j                   j                  |      d      }| j                  j
                  j                  |      }|r*t        j                  | j                  j                  |      S |S )a|  Sets the serving status of the specified version.

    Args:
      service_name: str, The service name
      version_id: str, The version to delete.
      serving_status: The serving status to set.
      block: bool, whether to block on the completion of the operation

    Returns:
      The completed Operation if block is True, or the Operation to wait on
      otherwise.
    r   )r;   r;   )r+   r   r   )
r,   )AppengineAppsServicesVersionsPatchRequestr   Versionr/   r   r   r   rO   rP   )r2   r   r   serving_statusblockpatch_requestrG   s          r$   SetServingStatusz#AppengineApiClient.SetServingStatus  s     MMKK  l,6 ! 8%%N%C"	 L $M
 2288GI--dkk.I.I.79 9 r&   c                    g }|D ]  }| j                   j                  | j                  |j                  |j                              }	 t        j                  | j                  j                  |ddd      D ]0  }|j                  t        j                  j                  |             2  |S # t        j                  $ r Y w xY w)zProduces a generator of all instances for the given versions.

    Args:
      versions: list of version_util.Version

    Returns:
      A list of instances_util.Instance objects for the given versions
    r6   	instancesd   pageSizefield
batch_sizebatch_size_attribute)r,   1AppengineAppsServicesVersionsInstancesListRequestr   rb   rT   r   YieldFromListr/    apps_services_versions_instancesappendr   InstanceFromInstanceResourcer   r   )r2   versionsr   r   r3   instances         r$   ListInstancesz AppengineApiClient.ListInstances  s     IOO$$W__gjjA P Cg"00KK88!+-H 

%%::8DF-	   !22 s   	A!B..CCc           
         | j                         }t        j                  dj                  |             t	        j
                  ||r|gnd      }| j                  |      }t        j                  dj                  t        t        t        |                         t        j                  ||r|gnd|      }t        t        ||            }| j                  |      S )aD  Generator of all instances, optionally filtering by service or version.

    Args:
      service: str, the ID of the service to filter by.
      version: str, the ID of the version to filter by.
      version_filter: filter function accepting version_util.Version

    Returns:
      generator of instance_util.Instance
    zAll services: {0}NzVersions: {0})ListServicesr   rM   rN   r   GetMatchingServicesListVersionslistr   strr   GetMatchingVersionsr   r   )r2   rb   r   version_filterservicesr   s         r$   GetAllInstancesz"AppengineApiClient.GetAllInstances  s       "HII!((23//w7)D2H   *HIIo$$T#c8*<%=>?//w7)D';HF>845Hh''r&   c                 *   | j                   j                  |j                         | j                   j                  |            }| j                  j
                  j                  |      }t        j                  | j                  j                  |      S )a!  Enable debugging of a Flexible instance.

    Args:
      res: A googleclousdk.core.Resource object.
      ssh_key: str, Public SSH key to add to the instance. Examples:
        `[USERNAME]:ssh-rsa [KEY_VALUE] [USERNAME]` ,
        `[USERNAME]:ssh-rsa [KEY_VALUE] google-ssh {"userName":"[USERNAME]",`
        `"expireOn":"[EXPIRE_TIME]"}`
        For more information, see Adding and Removing SSH Keys
        (https://cloud.google.com/compute/docs/instances/adding-removing-ssh-
        keys).

    Returns:
      The completed Operation.
    )sshKey)r+   debugInstanceRequest)
r,   2AppengineAppsServicesVersionsInstancesDebugRequestRelativeNameDebugInstanceRequestr/   r   Debugr   rO   rP   )r2   resssh_keyr3   rG   s        r$   DebugInstancez AppengineApiClient.DebugInstance  s~      mmNN!]]??w?O O QG <<BB7KI++DKK,G,G,57 7r&   c                     | j                   j                  |j                               }| j                  j                  j                  |      }t        j                  | j                  j                  |      S )zDelete a Flexible instance.

    Args:
      res: A googlecloudsdk.core.Resource object.

    Returns:
      The completed Operation.
    r*   )	r,   3AppengineAppsServicesVersionsInstancesDeleteRequestr   r/   r   r   r   rO   rP   )r2   r   r3   rG   s       r$   DeleteInstancez!AppengineApiClient.DeleteInstance  sf     mmOO P !G<<CCGLI++DKK,G,G,57 7r&   c                     | j                   j                  |j                               }| j                  j                  j                  |      S )a  Describe the given instance of the given version of the given service.

    Args:
      res: A googlecloudsdk.core.Resource object.

    Raises:
      apitools_exceptions.HttpNotFoundError: If instance does not
        exist.

    Returns:
      Version resource object from the API
    r*   )r,   0AppengineAppsServicesVersionsInstancesGetRequestr   r/   r   r1   )r2   r   r3   s      r$   GetInstanceResourcez&AppengineApiClient.GetInstanceResource  sE     mmLL M !G;;77;;GDDr&   c                 z    | j                  ||| j                  j                  j                  j                  |      S )a5  Stops the specified version.

    Args:
      service_name: str, The service name
      version_id: str, The version to stop.
      block: bool, whether to block on the completion of the operation


    Returns:
      The completed Operation if block is True, or the Operation to wait on
      otherwise.
    )r   r,   r   r=   STOPPEDr2   r   r   r   s       r$   StopVersionzAppengineApiClient.StopVersion  s9       ::BB	 r&   c                 z    | j                  ||| j                  j                  j                  j                  |      S )a6  Starts the specified version.

    Args:
      service_name: str, The service name
      version_id: str, The version to start.
      block: bool, whether to block on the completion of the operation

    Returns:
      The completed Operation if block is True, or the Operation to wait on
      otherwise.
    )r   r,   r   r=   SERVINGr   s       r$   StartVersionzAppengineApiClient.StartVersion,  s9       ::BB	 r&   c                    | j                   j                  | j                               }g }t        j                  | j
                  j                  |ddd      D ]  }i }|j                  r>|j                  j                  j                  D ]  }|j                  ||j                  <    |j                  t        j                  | j                  |j                   |              |S )znLists all services for the given application.

    Returns:
      A list of service_util.Service objects.
    r   r   r   r   r   )r,    AppengineAppsServicesListRequestr.   r   r   r/   r   r   r   additionalPropertiesvaluekeyr   r   r   rW   rT   )r2   r3   r   rb   r   r   s         r$   r   zAppengineApiClient.ListServices>  s     mm<<  = "GH++!!7*Z9 m	]]..CCE%*[[-		
" Doo


t||WZZ
GI9 Or&   c                     | j                   j                  | j                  ||      | j                   j                  j                  j                        }| j
                  j                  j                  |      S )zDescribe the given version of the given service.

    Args:
      service: str, the ID of the service for the version to describe.
      version: str, the ID of the version to describe.

    Returns:
      Version resource object from the API.
    )r+   view)r,   'AppengineAppsServicesVersionsGetRequestr   ViewValueValuesEnumFULLr/   r   r1   )r2   rb   r   r3   s       r$   GetVersionResourcez%AppengineApiClient.GetVersionResourceR  sc     mmCC  '2mm556I6I$$ D QG ;;--11'::r&   c                 z   g }|D ]  }| j                   j                  | j                  |j                              }	 t	        j
                  | j                  j                  |ddd      D ]1  }|j                  t        j                  j                  ||             3  |S # t        j                  $ r Y w xY w)zLists all versions for the specified services.

    Args:
      services: A list of service_util.Service objects.
    Returns:
      A list of version_util.Version objects.
    r   r   r   r   r   )r,   (AppengineAppsServicesVersionsListRequestr   rT   r   r   r/   r   r   r   r   FromVersionResourcer   r   )r2   r   r   rb   r3   r   s         r$   r   zAppengineApiClient.ListVersionsb  s     HFF--gjj9 G ;g!//KK..!+-G //""66wHJ- " O	 !22 s   A"B$$B:9B:c                 ,   | j                   j                  dj                  | j                              }t	        j
                  | j                  j                  |ddd      }|D cg c]!  }t        j                  j                  |      # c}S c c}w )zList all regions for the project, and support for standard and flexible.

    Returns:
      List of region_util.Region instances for the project.
    zapps/{0}r*   	locationsr   r   r   )r,   !AppengineAppsLocationsListRequestrN   rW   r   r   r/   apps_locationsr   RegionFromRegionResource)r2   r3   regionslocs       r$   ListRegionszAppengineApiClient.ListRegions~  s     mm==t||, > .G &&""G;Z9G CJJ'3K11#6'JJJs   (&Bc                    | j                   j                  | j                  |            }| j                  j                  j                  |      }dj                  |      }t        j                  | j                  j                  ||      S )zDeletes the specified service.

    Args:
      service_name: str, Name of the service to delete.

    Returns:
      The completed Operation.
    r   r*   zDeleting [{}]rH   )
r,   "AppengineAppsServicesDeleteRequestr   r/   r   r   rN   r   rO   rP   )r2   r   r   rG   rI   s        r$   DeleteServicez AppengineApiClient.DeleteService  s     ]]EE))|)D F FN))00@I$$\2G++DKK,G,G,54;= =r&   c                     | j                   j                  | j                  |            }| j                  j                  j                  |      S )zGrabs details about a particular gcloud operation.

    Args:
      op_id: str, ID of operation.

    Returns:
      Operation resource object from API call.
    r*   )r,   !AppengineAppsOperationsGetRequest_FormatOperationr/   rP   r1   )r2   op_idr3   s      r$   GetOperationzAppengineApiClient.GetOperation  sH     mm==""5) > +G ;;&&**733r&   c                    | j                   j                  | j                         |      }t        j                  | j
                  j                  |ddd      }|D cg c]  }t        j                  |       c}S c c}w )zLists all operations for the given application.

    Args:
      op_filter: String to filter which operations to grab.

    Returns:
      A list of opeartion_util.Operation objects.
    )r+   r   
operationsr   r   r   )	r,   "AppengineAppsOperationsListRequestr.   r   r   r/   rP   r   	Operation)r2   	op_filterr3   r  ops        r$   ListOperationsz!AppengineApiClient.ListOperations  sw     mm>>__ ? G ))##WLZ9J 5??JbO%%b)J???s   A=c           	         t        j                  |j                  j                               }d|vrd|d<   	 t	        j
                  | j                  j                        }|j                  |      }	t!        j"                  dj                  t%        j&                  |	dd	                   |||	d
<   i |	d<   ||	d   d<   |rl|j)                         rd|j*                  i|	d   d<   nG|j-                         rd|j*                  i|	d   d<   n"|j/                         r|j*                  |	d   d<   t1        j2                  | j4                  j6                  |	      }|j8                  r'|j8                  j:                  j=                  d        |rd|	vri |	d<   |	d   j?                  |       d|	v r|	jA                  d      }g }tC        |jE                               D ]E  \  }}|jG                  | j4                  j6                  jH                  jK                  ||             G | j4                  j6                  jI                  |      |_&        	 |jN                  jP                  j:                  j=                  tS        jT                  d             ||_,        |S # t        $ rH}
t        j                  dj                  |j                  t        j                  |
                  d}
~
ww xY w# tV        $ r Y hw xY w)a  Constructs a Version resource for deployment.

    Args:
      service_config: ServiceYamlInfo, Service info parsed from a service yaml
        file.
      manifest: Dictionary mapping source files to Google Cloud Storage
        locations.
      version_id: str, The version of the service.
      build: BuildArtifact, The build ID, image path, or build options.
      extra_config_settings: dict, client config settings to pass to the server
        as beta settings.
      service_account_email: identity of this deployed version. If not set,
        Admin API will fallback to use the App Engine default appspot SA.

    Returns:
      A Version resource whose Deployment includes either a container pointing
        to a completed image, or a build pointing to an in-progress build.
    
entrypoint zc[{f}] could not be converted to the App Engine configuration format for the following reason: {msg})fmsgNzConverted YAML to JSON: "{0}"   T)indent	sort_keysrV   
deploymentfilesimage	containercloudBuildIdr	   cloudBuildOptionsc                     | j                   S r   r   )xs    r$   <lambda>z;AppengineApiClient._CreateVersionResource.<locals>.<lambda>  s    r&   r1  betaSettings)r   r   )r   r   )-copydeepcopyparsedToDictr   GetSchemaParserr/   r   ConvertValue
ValueErrorr   ConfigErrorrN   filesix	text_typer   rM   jsondumpsIsImagery   rv   ro   r   r   r,   r   envVariablesr   sortupdategetsorteditemsr   BetaSettingsValueAdditionalPropertyr4  r*  r+  operator
attrgetterAttributeErrorrT   )r2   r   r   r   r	   r   r   config_dictschema_parserjson_version_resourceer   	json_dict
attributesr   r   s                   r$   r   z)AppengineApiClient._CreateVersionResource  s   2 -- 5 5 < < >?K ;&"$k,<"224;;3G3GHm+88E II-44

(dCE F (0E,-*,,'3;,'0	U%%<
l+K8 ??E,,8
l+G4 ! 	l+,?@001F1F1FH $$##88== >  	4	402n-N+223HI ..'++N;ijy01*#uMM!!33FFu G &	' 2 '+mm&;&;&M&M) 'N '+#
!!''<<AA!!%( B * %A  <""3396##q)9 4: 4;< <<v  
s+   :J AK. 	K+#AK&&K+.	K:9K:c                    d}| j                   j                         }|D cg c]  } | j                   j                  di |  c}|_        | j                   j	                  | j                         ||      }| j                  j                  j                  |      }t        j                  dj                  |j                  |             t        j                  | j                  j                  |      S c c}w )zUpdates an application's dispatch rules.

    Args:
      dispatch_rules: [{'service': str, 'domain': str, 'path': str}], dispatch-
          rules to set-and-replace.

    Returns:
      Long running operation.
    zdispatchRules,r+   applicationr   4Received operation: [{operation}] with mask [{mask}]rG   mask )r,   r<   UrlDispatchRuledispatchRulesAppengineAppsPatchRequestr.   r/   r0   r   r   rM   rN   r+   r   rO   rP   )r2   dispatch_rulesupdate_maskapplication_updaterupdate_requestrG   s          r$   UpdateDispatchRulesz&AppengineApiClient.UpdateDispatchRules#  s     #K2241?(A1?A )F(E(E(J(J1?(A$]]<<__& =  N
   &&~6IIIDKK.. L   ++DKK,G,G,57 7(As   #C7c                    d}| j                   j                         }||_        | j                   j                  | j	                         ||      }| j
                  j                  j                  |      }t        j                  dj                  |j                  |             t        j                  | j
                  j                  |      S )zUpdates an application's database_type.

    Args:
      database_type: New database type to switch to

    Returns:
      Long running operation.
    databaseTyperU  rW  rX  )r,   r<   re  r]  r.   r/   r0   r   r   rM   rN   r+   r   rO   rP   )r2   database_typer_  r`  rb  rG   s         r$   UpdateDatabaseTypez%AppengineApiClient.UpdateDatabaseTypeB  s     !K224&3#]]<<__& =  N
   &&~6IIIDKK..{ L 4 5 ++DKK,G,G,57 7r&   c                     | j                   j                  | j                  |      | j                   j                  |            }| j                  j
                  j                  |      S )zChecks if the service contains a Gen1 app.

    Args:
      service_name: str, The service name
      project_id: str, The project id

    Returns:
      boolean, True if the service contains a Gen1 app, False otherwise
    )rd   )r+   checkGen1AppIdRequest)r,   3AppengineAppsServicesMigrationCheckGen1appIdRequestr   CheckGen1AppIdRequestr/   apps_services_migrationCheckGen1appId)r2   r   
project_idr3   s       r$   CheckGen1AppIdz!AppengineApiClient.CheckGen1AppId]  sd     mmOO)),7"mmAA  B 
 P G ;;..==gFFr&   c                    |t         v r+| j                  j                  j                  j                  }n*| j                  j                  j                  j
                  }| j                  j                  | j                  |      | j                  j                  |||            }| j                  j                  j                  |      S )a3  Migrates the app.yaml file provided by the user to be Gen2 compatible.

    Args:
      project_id: str, The project id
      config_as_string: str, The config as a string
      runtime: str, The runtime
      service_name: str, The service name

    Returns:
      str, The migrated config as a string
    )rd   configAsStringruntime)r+   migrateConfigYamlRequest)gen1_runtimesr,   MigrateConfigYamlRequestRuntimeValueValuesEnumGEN1_PYTHON27$MIGRATION_ASSIST_RUNTIME_UNSPECIFIED6AppengineAppsServicesMigrationMigrateConfigYamlRequestr   r/   rl  MigrateConfigYaml)r2   rn  config_as_stringrr  r   runtime_enumreqs          r$   rz  z$AppengineApiClient.MigrateConfigYamlo  s     -
--
0
0
G
G
U
U 
 --
0
0
G
G
l
l  --
N
N)),7!%!G!G +  "H "
 O C ;;..@@EEr&   c                    |t         v r+| j                  j                  j                  j                  }n*| j                  j                  j                  j
                  }| j                  j                  | j                  |      | j                  j                  |||            }| j                  j                  j                  |      }t        j                  | j                  j                  |      S )a  Migrates the code file provided by the user to Gen2 runtime.

    Args:
      project_id: str, The project id
      code_as_string: str, The code as a string
      runtime: str, The runtime
      service_name: str, The service name

    Returns:
      Long running operation
    )rd   codeAsStringrr  )r+   migrateCodeFileRequest)rt  r,   MigrateCodeFileRequestrv  rw  rx  4AppengineAppsServicesMigrationMigrateCodeFileRequestr   r/   rl  MigrateCodeFiler   rO   rP   )r2   rn  code_as_stringrr  r   r|  r3   rG   s           r$   r  z"AppengineApiClient.MigrateCodeFile  s     -
--
.
.
E
E
S
S 
 --
.
.
E
E
j
j  	JJ--l;#'==#G#G$+$ $H $ 	K 	
  33CCGLI++##Y r&   r   )NN)UNSPECIFIEDF)T)NNN)&__name__
__module____qualname____doc__r4   r9   rB   rR   r_   r   rn   rk   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r  r  r  r!  r   rc  rg  ro  rz  r  rZ  r&   r$   r    r    @   s    E
)2$J0'H^ +/*.Qf6 ,0+/%EN2; 7<=<A.A& "46(07.7E"&$(; 8K="4@. 4837dL7>76G$F@!r&   r    )2r  
__future__r   r   r   r5  r@  rK  apitools.base.pyr   r   r   r   googlecloudsdk.api_lib.appr	   rs   r
   r   r   r   r   r   r   googlecloudsdk.api_lib.app.apir   !googlecloudsdk.api_lib.cloudbuildr   r}   /googlecloudsdk.appengine.admin.tools.conversionr   googlecloudsdk.callioper   calliope_basegooglecloudsdk.corer   r   r   r>  	six.movesr   r   ReleaseTrackGAALPHABETAr   r%   rt  AppengineApiClientBaser    rZ  r&   r$   <module>r     s     K &  '    % > ' ? * 1 5 6 2 3 + 3 D E H 9 # * ) 
   !!4$$i##X 6 p2II pr&   