
    5                     (   d 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  G d
 de	j                        Z G d de	j                        Z G d dej"                        Zd Z	 ddZd Zd Zd Zd Zd Zd Zd Zd Zd Zy)z"Utilities for simulation commands.    N)Messages)base)binary_operations)
exceptions)
properties)yaml)GetFreshAccessTokenc                       e Zd ZdZy)InvalidFileErrorz"Error if a file is not valid JSON.N__name__
__module____qualname____doc__     Dlib/googlecloudsdk/command_lib/network_management/simulation/util.pyr   r      s    *r   r   c                       e Zd ZdZy)InvalidInputErrorz(Error if the user supplied is not valid.Nr   r   r   r   r   r       s    0r   r   c                   0     e Zd ZdZi Z fdZ	 ddZ xZS )TerraformToolsBinaryOperationz+BinaryOperation for Terraform Tools binary.c                 6    t        t        | 
  ddddd d| y )Nzterraform-toolsT)binarycheck_hiddeninstall_if_missingcustom_errorsr   )superr   __init__)selfkwargs	__class__s     r   r   z&TerraformToolsBinaryOperation.__init__)   s.    	
'7  	
 r   c                 $    ||d|g}|r|d|gz  }|S )Nz--verbosityz	--projectr   )r   commandterraform_plan_jsonproject	verbosityr    argss          r   _ParseArgsForCommandz2TerraformToolsBinaryOperation._ParseArgsForCommand2   s*     (-CD
{G$$dKr   )debug)r   r   r   r   r   r   r(   __classcell__)r!   s   @r   r   r   $   s    3- >Er   r   c                     | j                   j                         }|t        j                  j                  k(  ryt	        j
                  d      )zReturn API version based on args.

  Args:
    args: The argparse namespace.

  Returns:
    API version (e.g. v1alpha or v1beta).
  v1alpha1zUnsupported release track.)calliope_commandReleaseTrackr   ALPHAr   InternalError)r'   release_tracks     r   GetSimulationApiVersionFromArgsr2   ;   sA     ''446-d''---  !=>>r   c                 |    |dk(  r|st        d      S t        | |||      S |dk(  rt        | ||      S t        d      )a  Given a json containing the resources which are to be updated, it return a list of config changes.

  Args:
    proposed_changes_file: File path containing the proposed changes
    api_version: API Version
    file_format: Format of the file
    simulation_type: Type of simulation
    original_config_file: Original config changes file provided in case of GCP
      config

  Returns:
    List of config changes in the format accepted by API

  Raises:
    InvalidInputError: If file format is invalid
  gcpz*Original config changes file not provided.tfzInvalid file-format.)r   #ParseGCPSimulationConfigChangesFile"ParseTFSimulationConfigChangesFile)proposed_changes_fileapi_versionfile_formatsimulation_typeoriginal_config_files        r   PrepareSimulationChangesr=   L   s`    0 EKLL.	  D-{O  	011r   c                 B    | dk(  ryt        dj                  |             )Ncompute#firewallcompute.googleapis.com/Firewallz7Only Firewall resources are supported. Instead found {})r   format)resource_types    r   MapResourceTyperC   u   s,    ((,?FF
	 r   c                 &   |st        d       t                |dk(  r3t        |       j                  |t        |       j	                               S |dk(  r3t        |       j                  |t        |       j                               S t        d      )z9Parse and map the appropriate simulation type to request.zNo new changes to simulate.zshadowed-firewall)configChangesshadowedFirewallSimulationDatazconnectivity-test)rE   connectivityTestSimulationDatazInvalid simulation-type.)printexitr   
SimulationShadowedFirewallSimulationDataConnectivityTestSimulationDatar   )r9   config_changes_listr;   s      r   MapSimulationTypeToRequestrN      s     
	
'(F++K ++)'/(

(
(
*	 ,   ++K ++)'/(

(
(
*	 ,   	455r   c                     d| vrt        d      | d   }t        j                  j                  j                  j                         }dj                  ||      | d<   y )Nnamez0`name` key missing in one of resource(s) config.zprojects/{}/global/firewalls/{}selfLink)r   r   VALUEScorer%   GetrA   )proposed_resource_configrP   
project_ids      r   AddSelfLinkGCPResourcerW      s[    ++
N
OO	!&	)$  %%--113*'..z4@ :&r   c           	         	 t        j                  |       }	 t        j                  |      }g }g }g }	|D ]4  }
d|
vrt        d      d|
vrt        d      |j                  |
d          6 |D ]w  }d|vrt        d      d|vrd	|d<   t        ||||      }t        |      j                  |t        |d         t        j                  |d
            }|	j                  |       y t        |      j                  j                  }|D ]i  }
|
d   }||vsd|i}t        |      j                  |j                  t        |
d         t        j                  |d
            }|	j                  |       k t        ||	|      S # t         j                  $ r}t        dj	                  |             d}~ww xY w# t         j                  $ r}t        dj	                  |            d}~ww xY w)z:Parse and convert the config changes file into API Format.'Error parsing config changes file: [{}]Nz,Error parsing the original config file: [{}]kindz0`kind` key missing in one of resource(s) config.rQ   z9`selfLink` missing in one of original resource(s) config.	directionINGRESST)	sort_keys
updateType	assetTypeproposedConfigBody)r   	load_pathYAMLParseErrorr   rA   r   appendIdentifyChangeUpdateTyper   ConfigChangerC   jsondumpsUpdateTypeValueValuesEnumDELETErN   )r8   r9   r;   r<   proposed_resources_config
unused_reforiginal_resources_configoriginal_config_resource_listupdate_resource_listrM   original_resource_configrU   update_typeconfig_changeenumoriginal_self_linkresource_configs                    r   r6   r6      sE    $/D E $/C D #%";--
<  11
E  "(()A*)MN #< #<--
<  22 /8{+* %	K [)66!":6"BC::&>$O 7 M
 }-/ #<2 
+		+	+	E	E$";1*=!55#%78o{+88[[#$<V$DE!ZZ4H 9 m
   / #< 
$&
 E 
		 
1889NO  
		 
6== 	
 s.   F F7 F4F//F47G)
G$$G)c                    t        t        j                  j                  j                  j                               dd} t               d| t        j                  j                  j                  j                         |      }|j                  r=t        j                  d      }|j                  j                  d      D ]
  } ||        t        j                  |j                        S )z5Parses and converts the tf plan file into CAI Format.)accounttrue)GOOGLE_OAUTH_ACCESS_TOKENUSE_STRUCTURED_LOGGINGztfplan-to-cai)r#   r$   r%   envN
)r	   r   rR   rS   rw   rT   r   r%   stderrr   !DefaultStreamStructuredErrHandlersplitrg   loadsstdout)r8   env_varsoperation_resulthandlerlines        r   ParseTerraformPlanFileTFToolsr      s     $7##((00446$ !'	( 524/$$,,002
	 AA$GG ''--d3dm 4 
$++	,,r   c                 <   	 t        j                  |       }t        |      j                  j                  }g }g }g }dg}	|d   D ]m  }
|
d   |	vr|
d   }|d   }|d   r|d   d	   }t        |      d
kD  r|j                         Bd|v r|j                         Xd|v s]|j                         o t        |       }t        |||||      }t        ||||      }t        |||      S # t         j                  $ r}t        dj	                  |             d}~ww xY w)z<Parses and converts the config changes file into API Format.rY   Ngoogle_compute_firewallresource_changestypechangeactionsbefore	self_link   updatedelete)r   rb   rc   r   rA   r   rf   ri   lenrd   r   ,ParseAndAddResourceConfigToConfigChangesList%AddDeleteResourcesToConfigChangesListrN   )r8   r9   r;   tf_planrl   rs   update_resources_listdelete_resources_listtainted_resources_listsupported_resource_typesresource_change_configresource_change_objectr   resource_self_link
gcp_configrM   s                   r   r7   r7   	  sp   
nn23G 
+		+	+	E	E$78 '(: ;f%-EE3H=$Y/G h'1(;KH
7|a##$67	W	""#56	W	""#56/ !<2 --BC* E
 >0$ 
$&
 g 
		 
1889NO s   C) )D<DDc                    g }| d   D ]  }d|vrt        d      |d   }|d   j                  dd      }|dk7  s||v r6|d   d	   }	d
|	d<   ||v r|j                  }
||	d<   n|j                  }
||	d<   d|	vrd|	d<   t	        |      j                  |
|t        j                  |	            }|j                  |        |S )zOParses the resources from gcp_config file and adds them to config_changes_list.resource_body
asset_typez"Error parsing config changes file.rP   z//compute.googleapis.comz%https://www.googleapis.com/compute/v1r@   resourcedatar?   rZ   rQ   r[   r\   r^   )	r   replaceUPDATEINSERTr   rf   rg   rh   rd   )r   r   ro   rs   r9   rM   resource_objectr   r   rU   rq   rr   s               r   r   r   H  s    #O4o?*BCC .J'//"$KI
 	77...z:6B'9V$ ((KKk-6z*KKk-6z* 
4	409 -[)66::&>? 7 M
 }-I 5L 
r   c                     | D ]Q  }d|i}t        |      j                  |j                  dt        j                  |            }|j                  |       S |S )zKAdds the resources having update type as delete to the config_changes_list.rQ   r@   r^   )r   rf   rj   rg   rh   rd   )r   rM   rs   r9   r   ru   rr   s          r   r   r   z  sb     2!#56O[)66;;3::o6 7 M
 }- 2 
r   c                     t        |      j                  j                  }d| v r'| d   }||v r|j                  |       |j                  S yt        |        |j                  S )z=Given a proposed resource config, it returns the update type.rQ   N)r   rf   ri   rd   r   rW   r   )rU   original_resource_config_listr9   ro   rs   r   s         r   re   re     sh     
+		+	+	E	E$++(4I11!!),[[ 2 34;;r   )N)r   rg   4googlecloudsdk.api_lib.network_management.simulationr   googlecloudsdk.callioper   &googlecloudsdk.command_lib.util.anthosr   googlecloudsdk.corer   r   r   %googlecloudsdk.core.credentials.storer	   Errorr   r   BinaryBackedOperationr   r2   r=   rC   rN   rW   r6   r   r7   r   r   re   r   r   r   <module>r      s    )  I ( D * * $ E+z'' +1
(( 1$5$K$K .?, &2R64JZ-.<~/d r   