
    1V                     p   d Z ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
 ddlmZ dd	lmZ d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 G d de      Zi dej0                  dej2                  dej2                  dej4                  dej4                  dej0                  dej0                  dej2                  dej2                  dej4                  dej4                  dej4                  dej2                  dej2                  d ej4                  d!ej0                  d"ej2                  ej2                  ej4                  ej4                  ej0                  ej0                  ej2                  ej2                  ej4                  ej4                  ej4                  ej2                  ej2                  ej4                  d#Zd$Zd%Zd& Zd' Zd( Z d) Z!d* Z"d+ Z#d, Z$d- Z%d. Z&d/ Z'd0 Z(d1 Z)d2 Z*d3 Z+d4 Z,d5 Z-d6 Z.d7 Z/d8 Z0d9 Z1d: Z2d; Z3d< Z4d= Z5	 dDd>Z6d? Z7d@ Z8dA Z9dB Z:dC Z;y)Ez-Utility functions for GCE OS Config commands.    )absolute_import)division)unicode_literals)Enum)encoding)apis)base)
exceptions)common_args)log)
properties)	resources)yamlNc                       e Zd ZdZdZdZdZy)InstanceDetailsStatesz9Indicates instance progress during a patch job execution.         N)__name__
__module____qualname____doc__NOTIFIEDPATCHINGFINISHED     9lib/googlecloudsdk/command_lib/compute/os_config/utils.pyr   r   $   s    A(((r   r   instancesAckedinstancesApplyingPatchesinstancesDownloadingPatchesinstancesFailedinstancesInactiveinstancesNotifiedinstancesPendinginstancesRebootinginstancesStartedinstancesSucceeded instancesSucceededRebootRequiredinstancesTimedOutinstancesRunningPrePatchStepinstancesRunningPostPatchStepinstancesNoAgentDetectedackedInstanceCountapplyingPatchesInstanceCount)downloadingPatchesInstanceCountfailedInstanceCountinactiveInstanceCountnotifiedInstanceCountpendingInstanceCountrebootingInstanceCountstartedInstanceCountsucceededInstanceCount$succeededRebootRequiredInstanceCounttimedOutInstanceCountprePatchStepInstanceCountpostPatchStepInstanceCountnoAgentDetectedInstanceCount)zgs://z&https://www.googleapis.com/storage/v1/zhttps://storage.googleapis.com/d   c                     | j                   r| j                   S | j                  rt        | j                  t              S y)z-Returns the batch size for listing resources.N)	page_sizelimitmin_MAX_LIST_BATCH_SIZE)argss    r   GetListBatchSizerD   U   s/    	^^>>zztzz/00r   c                 (    dj                  | |g      S )z.Returns the URI path of a GCP parent resource./join)parent_name	parent_ids     r   GetParentUriPathrK   _   s    	;	*	++r   c                     t        d|       S )z&Returns the URI path of a GCP project.projectsrK   )projects    r   GetProjectUriPathrP   d   s    	*g	..r   c                 B    t        t        d|       t        d|            S )z/Returns the URI path of projects/*/locations/*.rM   	locationsrN   )rO   locations     r   GetProjectLocationUriPathrT   i   s#    	z7+{H-
/ /r   c                     t        d|       S )z%Returns the URI path of a GCP folder.foldersrN   )folders    r   GetFolderUriPathrX   p   s    	)V	,,r   c                     t        d|       S )z+Returns the URI path of a GCP organization.organizationsrN   )organizations    r   GetOrganizationUriPathr\   u   s    	/<	88r   c                 ,    dj                  d| d|g      S )z.Returns the URI path of an osconfig patch job.rF   rM   	patchJobsrG   )rO   	patch_jobs     r   GetPatchJobUriPathr`   z   s    	:wY?	@@r   c                 *    | j                  d      d   S )z0Returns the name of a GCP resource from its URI.rF   r   )split)uris    r   GetResourceNamerd      s    	3	r   c                 *    dj                  | d|g      S )z6Returns the relative path of an osconfig guest policy.rF   guestPoliciesrG   )parentguest_policys     r   GetGuestPolicyRelativePathri      s    	6?L9	::r   c                 *    dj                  | d|g      S )z>Returns the relative path of an osconfig os policy assignment.rF   osPolicyAssignmentsrG   )rg   os_policy_assignments     r   !GetOsPolicyAssignmentRelativePathrm      s    	602FG	HHr   c                 .    t        j                  d|       S )z7Returns the messages module with the given api_version.osconfig)r   GetMessagesModule)api_versions    r   GetApiMessagerr      s    			
K	88r   c                    | j                   j                         }|t        j                  j                  k(  ry|t        j                  j                  k(  ry|t        j                  j
                  k(  ryt        j                  |      )z7Return api version for the corresponding release track.v1alphav1betav1calliope_commandReleaseTrackr	   ALPHABETAGAcore_exceptionsUnsupportedReleaseTrackErrorrC   release_tracks     r   GetApiVersionr      l    ''446-d''---))...)),,,

6
6}
EEr   c                    | j                   j                         }|t        j                  j                  k(  ry|t        j                  j                  k(  ry|t        j                  j
                  k(  ryt        j                  |      )z:Return v2 api version for the corresponding release track.v2alphav2betav2rw   r   s     r   GetApiVersionV2r      r   r   c                     | j                   j                         }|t        j                  j                  k(  ry|t        j                  j                  k(  r	 yt        j                  |      )z8Returns api version for the corresponding release track.zkTo check operation status, run: gcloud alpha compute os-config os-policy-assignments operations describe {}zeTo check operation status, run: gcloud compute os-config os-policy-assignments operations describe {})rx   ry   r	   rz   r|   r}   r~   r   s     r   !GetOperationDescribeCommandFormatr      s`    ''446-d''---;)),,,	78 
6
6}
EEr   c           	         | j                  dj                  |      d      }t        j                  dj                  ||      dj                  t        j
                  j                  j                  t        j
                  j                  j                              j                  |       |j                  dd	t        d
j                  ||             |j                  ddt        dj                  ||             y)z;Adds project, folder, and organization flags to the parser.zi      The scope of the {}. If a scope is not specified, the current project is
      used as the default.T)helpmutexzThe project of the {} {}.aj        The project name to use. If a project name is not specified, then the
      current project is used. The current project can be listed using gcloud
      config list --format='text(core.project)' and can be set using gcloud
      config set project PROJECTID.

      `--project` and its fallback `{core_project}` property play two roles. It
      specifies the project of the resource to operate on, and also specifies
      the project for API enablement check, quota, and billing. To specify a
      different project for quota and billing, use `--billing-project` or
      `{billing_project}` property.
      )core_projectbilling_project)help_text_to_prependhelp_text_to_overwritez--folder	FOLDER_IDzThe folder of the {} {}.)metavartyper   z--organizationORGANIZATION_IDzThe organization of the {} {}.N)	add_groupformatr   ProjectArgumentr   VALUEScorerO   billingquota_projectAddToParseradd_argumentstr)parsernounverbparent_resource_groups       r   AddResourceParentArgsr      s     **$fTl	 +  6==dDI
 &!((--55$++33AA  CD EPK#E%$$%,,T48	 %  $$+224>	 % r   c                 ,    dj                  d| d|g      S )z5Returns the URI path of an osconfig patch deployment.rF   rM   patchDeploymentsrG   )rO   patch_deployments     r   GetPatchDeploymentUriPathr      s    	:w(:<LM	NNr   c                 ,    dj                  | |d|g      S )z1Returns the URI path of an osconfig guest policy.rF   rf   rG   )parent_typerI   	policy_ids      r   GetGuestPolicyUriPathr      s    	;_iH	IIr   c           	         	 t        j                  |       }t        |t              s$t        j                  dj                  |             t        |j                               }	 t        j                  ||      }||fS # t         j                  $ r=}t        j                  dj                  | t        j                  |                  d}~wt         j                  $ r=}t        j                  dj                  | t        j                  |                  d}~ww xY w# t        $ r=}t        j                  dj                  | t        j                  |                  d}~ww xY w)z7Returns the resource message and update fields in file.z.Policy config file [{0}] cannot be parsed. {1}Nz6Policy config file [{0}] cannot be opened or read. {1}zGPolicy config file [{0}] is not a properly formatted YAML or JSON file.zKPolicy config file [{0}] is not a properly formatted YAML or JSON file. {1})r   	load_pathYAMLParseErrorr
   BadFileExceptionr   six	text_typeFileLoadError
isinstancedictlistkeysr   PyValueToMessageAttributeError)	file_pathresource_message_typeresource_to_parseeupdate_fieldsresources         r   "GetResourceAndUpdateFieldsFromFiler      sH   	*y1 
%t	,

%
%	y!# # (--/0-9(()>):<H M	""1 
		 *

%
%8??s}}Q'	)* * 
		 *

%
%@GGs}}Q'	)* **  9

%
%	F9cmmA&679 99s;   A? %D  ?D8C

D 8DD 	E&)8E!!E&c                     d}t         D ]4  }|j                  |      st        j                  j	                  |      } n |syt        |d      rt        |d      s%t        j                  | dj                  |            |j                  j                  d      }t        |      dk7  s|d   j                         s%t        j                  | dj                  |            |j                  |d	   t        |d         d
S )zReturns information for a Google Cloud Storage object.

  Args:
      arg_name: The name of the argument whose value may be a GCS object path.
      path: A string whose value may be a GCS object path.
  Nbucketobjectz7The provided Google Cloud Storage path [{}] is invalid.#r   r   zWThe provided Google Cloud Storage path [{}] does not contain a valid generation number.r   )r   r   generationNumber)_GCS_PREFIXES
startswithr   REGISTRYParsehasattrr
   InvalidArgumentExceptionr   r   rb   lenisdigitr   int)arg_namepathobj_refprefixobj_strs        r   GetGcsParamsr     s     'fv""((.g 
 
	(	#77H+E

-
-AHHNP P NN  %'\Qgaj002

-
-	#VD\+ + 
gaj/
 r   c                     ~ t        |      }t        |      }t        |j                  |j                        \  }}||_        |j                          d|j                  v rdj                  |      |_	        |S )zJReturns modified request with parsed OS policy assignment and update mask.update,)
r   rr   r   fileOSPolicyAssignmentoSPolicyAssignmentsortcommand_pathrH   
updateMask)refrC   reqrq   messagespolicy_assignment_configr   s          r   ParseOSConfigAssignmentFiler   1  sr    	d#+;'(6yy(--/3#"""XXm,CN	*r   c                     |dk(  r| j                         S |dk(  r| j                         S |dk(  r| j                         S t        j                  |      )zBReturns the orchestration scope message for the given API version.r   r   r   ),GoogleCloudOsconfigV2alphaOrchestrationScope+GoogleCloudOsconfigV2betaOrchestrationScope'GoogleCloudOsconfigV2OrchestrationScoper}   r~   r   rq   s     r   GetOrchestrationScopeMessager   @  sX    I@@BBh??AAd;;==

6
6{
CCr   c                     |dk(  r| j                         S |dk(  r| j                         S |dk(  r| j                         S t        j                  |      )zKReturns the orchestration scope selector message for the given API version.r   r   r   )4GoogleCloudOsconfigV2alphaOrchestrationScopeSelector3GoogleCloudOsconfigV2betaOrchestrationScopeSelector/GoogleCloudOsconfigV2OrchestrationScopeSelectorr}   r~   r   s     r   $GetOrchestrationScopeSelectorMessager   L  sX    IHHJJhGGIIdCCEE

6
6{
CCr   c                     |dk(  r| j                         S |dk(  r| j                         S |dk(  r| j                         S t        j                  |      )zJReturns the resource hierarchy selector message for the given API version.r   r   r   )EGoogleCloudOsconfigV2alphaOrchestrationScopeResourceHierarchySelectorDGoogleCloudOsconfigV2betaOrchestrationScopeResourceHierarchySelector@GoogleCloudOsconfigV2OrchestrationScopeResourceHierarchySelectorr}   r~   r   s     r   #GetResourceHierarchySelectorMessager   X  sd    IVVX hUUW dQQS 
6
6{
CCr   c                     |dk(  r| j                         S |dk(  r| j                         S |dk(  r| j                         S t        j                  |      )z@Returns the location selector message for the given API version.r   r   r   )<GoogleCloudOsconfigV2alphaOrchestrationScopeLocationSelector;GoogleCloudOsconfigV2betaOrchestrationScopeLocationSelector7GoogleCloudOsconfigV2OrchestrationScopeLocationSelectorr}   r~   r   s     r   GetLocationSelectorMessager   j  s`    IMMO hLLN dKKMM

6
6{
CCr   c                    | j                   xsP |xr | j                  xs> | j                  xs0 |xr | j                  xs | j                  xs |xr | j
                  }|s|dfS d}d}d}	|r| j                  rg }|r| j                  rg }|r| j
                  rg }	| j                   r6g }| j                   j                  d      D ]  }
|j                  d|
z           | j                  r6g }| j                  j                  d      D ]  }|j                  d|z           | j                  r3g }	| j                  j                  d      D ]  }|	j                  |        |j                  st        ||      |_        d}d}|j                  j                  r9|j                  j                  D ]   }|j                  r|}|j                  s|}" |st        ||      }|st        ||      }||g|j                  _
        |j                  st        ||      |_        |j                  st        ||      |_        |||j                  _        |||j                  _        |	|	|j                  _        |dfS )a  Sets selectors inside policy orchestrator.

  Args:
    args: args to the command
    req: request
    messages: messages for selected v2 API version
    api_version: api version
    orchestrator: orchestrator to set selectors in
    use_clear: if true, clear_projects flag is used to clear selectors
    (optional)

  Returns:
    modified request, boolean  indicating if selectors were set
  FNr   z	projects/zfolders/T)include_projectsclear_projectsinclude_foldersclear_foldersinclude_locationsclear_locationsrb   appendorchestrationScoper   	selectorsresourceHierarchySelectorlocationSelectorr   r   r   includedProjectsincludedFoldersincludedLocations)rC   r   r   rq   orchestrator	use_clearselectors_setincluded_projectsincluded_foldersincluded_locations
project_id	folder_idrS   hierarchy_selectorlocation_selectorselectors                   r   $ModifyOrchestratorPolicySetSelectorsr  z  s   $  .

+++.			. 
***. 
			.
 
,,,  
:  4&& 4%% 4''	++11#6
{Z78 7 
))//4	j945 5 
**005) 6 
	(	($X{; #
 $$.. 33==		+	+%$$$	 >
 
=+	<+ /,!!+
 
	5	5+HkB 0 
	+	+"8[9 & " 00A ! 00@ #;M&&8	dr   c                    t        |      }t        |      }|j                         }|j                  dk(  r#t	        |j
                  |j                        \  }}d}|dk(  r-|j                         }|j                         |_        ||_	        nc|dk(  r-|j                         }|j                         |_        ||_        n1|dk(  r,|j                         }|j                         |_        ||_        ||j                  _        |j"                  r|j"                  |j                  _        |j                  j'                         |_        |j(                  j'                         |_        t+        |||||      \  }}| j-                         |_        dj1                  |j2                  j5                  d      dd       |_        |S )FReturns modified request with parsed orchestartor's policy assignment.upsertNr   r   r   rF   )r   rr   r   actionr   policy_file,GoogleCloudOsconfigV2alphaPolicyOrchestrator.GoogleCloudOsconfigV2alphaOrchestratedResourceorchestratedResource,googleCloudOsconfigV2alphaPolicyOrchestrator+GoogleCloudOsconfigV2betaPolicyOrchestrator-GoogleCloudOsconfigV2betaOrchestratedResource+googleCloudOsconfigV2betaPolicyOrchestrator'GoogleCloudOsconfigV2PolicyOrchestrator)GoogleCloudOsconfigV2OrchestratedResource'googleCloudOsconfigV2PolicyOrchestratorosPolicyAssignmentV1Payloadr   idupperstater  NamepolicyOrchestratorIdrH   rg   rb   )r   rC   r   rq   r   r   _req_orchestrators           r   #ModifyOrchestrorPolicyCreateRequestr*    s     %+;'( &88:	[[H$F(55%!q ILLN??A ) 8HC4hKKM>>@ ) 7GC3dGGI::< ) 3CC/  ''C 
^^/3~~)), KK--/::++-/
C;(8&#q
 !XXZ#xx

((-cr23#*	*r   c                     t        |      }t        |      }d}|dk(  r|j                  }n#|dk(  r|j                  }n|dk(  r|j                  }g }|j
                  r0|j
                  j                         |_        |j                  d       |j                  rEt        |j                  |j                        \  }}||j                  _        |j                  d       |j                  r,|j                  |j                  _        |j                  d       |j                  r0|j                  j                         |_        |j                  d       t!        |||||d	
      \  }}	|	r|j                  d       dj#                  |      |_        |S )r  Nr   r   r   r  z5orchestrated_resource.os_policy_assignment_v1_payloadzorchestrated_resource.idr%  T)r  zorchestration_scope.selectorsr   )r   rr   r  r  r!  r  r$  r   r  r   r   r  r"  r   r#  r%  r  rH   r   )

unused_refrC   r   rq   r   r)  update_maskr   r(  modifieds
             r   #ModifyOrchestrorPolicyUpdateRequestr/  !  sw     %+;'( IGGhFFdBB+	[["kk//1x 	$F(55%!q 	! ))E ? 
^^/3~~)),12	ZZ!ZZ--/w6
C;(8D-#x 6788K(#.	*r   c                 0    |xj                   dz  c_         |S )z*Extends request with global location part.z/locations/global)rg   r,  unused_argsr   s      r   !ModifyOrchestrorPolicyListRequestr3  W  s     **##*	*r   c                     |j                   rAt        j                  j                  t	        |      j                  | j                               | S )zReminds user of the command to check operation status.

  Args:
    response: Response from CreateOsPolicyAssignment
    args: gcloud args

  Returns:
    The original response
  )async_r   outPrintr   r   name)responserC   s     r   &LogOutOperationCommandForAsyncResponser:  ^  s8     
[[GGMM)$/66x}}EG	/r   c                 .    |j                   dz   |_         |S )Nz/projectFeatureSettings)r8  r1  s      r   $UpdateProjectFeatureSettingsResourcer<  p  s    XX11#(	*r   )F)<r   
__future__r   r   r   enumr   apitools.base.pyr   googlecloudsdk.api_lib.utilr   googlecloudsdk.callioper	   r
   $googlecloudsdk.command_lib.util.argsr   googlecloudsdk.corer}   r   r   r   r   r   r   r   r   r   INSTANCE_DETAILS_KEY_MAPr   rB   rD   rK   rP   rT   rX   r\   r`   rd   ri   rm   rr   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r*  r/  r3  r:  r<  r   r   r   <module>rE     s   4 &  '  % , ( . < = # * ) $ 
D "+44"  5 > >" "#8#A#A	"
 ,55" .77" .77" -66" /88" -66" /88" '(=(F(F" .77" #$9$B$B" $%:%C%C"   5 > >!"& /88'"( #$9$B$B)"* (='E'E0992;;2;;1::3<<1::3<<,A,J,J2;;!6!?!?"7"@"@$9$B$BC" H4  ,
/
/-
9
A

;
I
9
FFF$NO
J
#> F	D	DD$D" ?Dnb3l3l$r   