
    VhF                        d dl mZmZmZ eZd dlZd dlZd dlZd dl	Z	d dl
Z
dZ	 d dlmZ dZd dlmZ d dlmZmZ d dlmZ d d	lmZ d
 ZddZd Zd Z G d de      Z G d de      Z  G d de      Z! G d de      Z" ejF                  ejH                         G d de%             Z&y# e$ r  e
j                          ZdZY w xY w)    )absolute_importdivisionprint_functionN)OneViewClientTF)six)AnsibleModulemissing_required_lib	to_native)Mappingc                     i }| s|S | D ]4  }t        |t              r|j                  |       %d|t        |d      <   6 |S )z
    Transforms a list into a dictionary, putting values as keys.

    :arg list list_: List of values
    :return: dict: dictionary built
    Tsurrogate_or_strict)errors)
isinstancer   updater   )list_retvalues      r/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/module_utils/oneview.pytransform_list_to_dictr   %   sQ     C
 GeW%JJuBFC	%(=>?	G J    c                    |g n|}| s|S t        j                  | D cg c]  }||   |j                         f c}      }t        j                         }|D ]P  }||   }||v r@|D ]  }	|	|v s||	   |j                  |	         ||   ||<   ||   j	                  |       L|||<   R t        |j                               S c c}w )a  
    Merge two lists by the key. It basically:

    1. Adds the items that are present on updated_list and are absent on original_list.

    2. Removes items that are absent on updated_list and are present on original_list.

    3. For all items that are in both lists, overwrites the values from the original item by the updated item.

    :arg list original_list: original list.
    :arg list updated_list: list with changes.
    :arg str key: unique identifier.
    :arg list ignore_when_null: list with the keys from the updated items that should be ignored in the merge,
        if its values are null.
    :return: list: Lists merged.
    )collectionsOrderedDictcopypopr   listvalues)
original_listupdated_listkeyignore_when_nulli	items_mapmerged_itemsitemitem_keyignored_keys
             r   merge_list_by_keyr)   ;   s    " .5r;K''](S!C&!&&();(STI**,L 	*9y / *$&4+<+DHH[)* &/x%8L""))$/%)L"	* ##%&& )Ts   Cc                 f    t        | t              rt        j                  | d      S t	        |       S )NT)	sort_keys)r   r   jsondumpsstr)objs    r   _str_sortedr0   c   s&    #wzz#..3xr   c                 n    t        | t              r| j                         rt        |       } t	        |       S )z
    Convert value to string to enhance the comparison.

    :arg value: Any object type.

    :return: str: Converted value.
    )r   float
is_integerintr.   )r   s    r   _standardize_valuer5   j   s.     %E$4$4$6 E
u:r   c                       e Zd ZdZd Zy)OneViewModuleExceptionz
    OneView base Exception.

    Attributes:
       msg (str): Exception message.
       oneview_response (dict): OneView rest response.
   c                 r   d | _         d | _        t        |t        j                        r|| _         n/|| _        |r&t        |t
              r|j                  d      | _         | j                  r,t        j                  | | j                   | j                         y t        j                  | | j                          y )Nmessage)	msgoneview_responser   r   string_typesdictget	Exception__init__)selfdatas     r   r@   zOneViewModuleException.__init__   s     $dC,,-DH$(D!
4.88I.  tTXXt/D/DEtTXX.r   N)__name__
__module____qualname____doc__r@    r   r   r7   r7   z   s    /r   r7   c                   $     e Zd ZdZd fd	Z xZS )OneViewModuleTaskErrorz
    OneView Task Error Exception.

    Attributes:
       msg (str): Exception message.
       error_code (str): A code which uniquely identifies the specific error.
    c                 :    t         t        |   |       || _        y N)superrI   r@   
error_code)rA   r:   rM   	__class__s      r   r@   zOneViewModuleTaskError.__init__   s    $d4S9$r   rK   )rC   rD   rE   rF   r@   __classcell__)rN   s   @r   rI   rI      s    % %r   rI   c                       e Zd ZdZy)OneViewModuleValueErrorz
    OneView Value Error.
    The exception is raised when the data contains an inappropriate value.

    Attributes:
       msg (str): Exception message.
    NrC   rD   rE   rF   rG   r   r   rQ   rQ           	r   rQ   c                       e Zd ZdZy)OneViewModuleResourceNotFoundz
    OneView Resource Not Found Exception.
    The exception is raised when an associated resource was not found.

    Attributes:
       msg (str): Exception message.
    NrR   rG   r   r   rU   rU      rS   r   rU   c            
       (   e Zd ZdZdZdZdZdZdZ e	 e	d       e	d	       e	d	       e	d	d
       e	d       e	d	            Z
 e	 e	dd
            ZdZddZd Zd Zd Zej$                  d        Zd ZddZd Zd dZd Zd Zd Zy)!OneViewModuleBasezResource created successfully.zResource updated successfully.zResource deleted successfully.zResource is already present.zResource is already absent.zDifference found at key '{0}'. path)typer.   T)rY   no_logr4   )confighostnameusernamepasswordapi_versionimage_streamer_hostnamebool)rY   default)validate_etagNc                    | j                  ||      }t        ||      | _        | j                          | j	                          | j                  j
                  j                  d      | _        | j                  j
                  j                  d      | _        | j                  j
                  j                  d      xs i | _	        t        | j                  j
                  j                  d            | _        || _        y)z
        OneViewModuleBase constructor.

        :arg dict additional_arg_spec: Additional argument spec definition.
        :arg bool validate_etag_support: Enables support to eTag validation.
        )argument_specsupports_check_modestaterB   paramsoptionsN)_build_argument_specr   module_check_hpe_oneview_sdk_create_oneview_clientrh   r>   rg   rB   facts_paramsr   ri   validate_etag_support)rA   additional_arg_specro   rf   re   s        r   r@   zOneViewModuleBase.__init__   s     112EG\]#-Uhi##%##%[[''++G4
KK&&**62	 !KK..228<B .dkk.@.@.D.DY.OP%:"r   c                     t               }|j                  | j                         |r|j                  | j                         |r|j                  |       |S rK   )r=   r   ONEVIEW_COMMON_ARGSONEVIEW_VALIDATE_ETAG_ARGS)rA   rp   ro   merged_arg_specs       r   rj   z&OneViewModuleBase._build_argument_spec   sL    &t778 ""4#B#BC""#67r   c                 f    t         s+| j                  j                  t        d      t               y y )N	hpOneViewr:   	exception)HAS_HPE_ONEVIEWrk   	fail_jsonr	   HPE_ONEVIEW_IMP_ERRrA   s    r   rl   z(OneViewModuleBase._check_hpe_oneview_sdk   s(    KK!!&:;&GSf!g r   c                 R   | j                   j                  j                  d      rt        | j                   j                  d   t        | j                   j                  d   | j                   j                  d         | j                   j                  d   | j                   j                  d         }t	        |      | _        y | j                   j                  d   st	        j                         | _        y t	        j                  | j                   j                  d         | _        y )	Nr\   r]   r^   )userNamer^   r_   r`   )ipcredentialsr_   image_streamer_ipr[   )rk   rh   r>   r=   r   oneview_clientfrom_environment_variablesfrom_json_file)rA   r[   s     r   rm   z(OneViewModuleBase._create_oneview_client   s    ;;!!*-T[[//
;&*DKK4F4Fz4R]a]h]h]o]opz]{&|&*kk&8&8&G,0KK,>,>?X,Y[F #0"7D##H-"/"J"J"LD"/">">t{{?Q?QRZ?["\Dr   c                      y)a3  
        Abstract method, must be implemented by the inheritor.

        This method is called from the run method. It should contains the module logic

        :return: dict: It must return a dictionary with the attributes for the module result,
            such as ansible_facts, msg and changed.
        NrG   r|   s    r   execute_modulez OneViewModuleBase.execute_module  s     	r   c                    	 | j                   rI| j                  j                  j                  d      s$| j                  j
                  j                          | j                         }d|vrd|d<    | j                  j                  di | y# t        $ r[}dj                  d |j                  D              }| j                  j                  |t        j                                Y d}~yd}~ww xY w)	a  
        Common implementation of the OneView run modules.

        It calls the inheritor 'execute_module' function and sends the return to the Ansible.

        It handles any OneViewModuleException in order to signal a failure to Ansible, with a descriptive error message.

        rc   changedFz; c              3   2   K   | ]  }t        |        y wrK   r
   ).0es     r   	<genexpr>z(OneViewModuleBase.run.<locals>.<genexpr>'  s     !G1)A,!Gs   rw   NrG   )ro   rk   rh   r>   r   
connectiondisable_etag_validationr   	exit_jsonr7   joinargsrz   	traceback
format_exc)rA   resultrx   	error_msgs       r   runzOneViewModuleBase.run  s    	S)){{))--o>''22JJL((*F&$)y!!DKK!!+F+% 	S		!G	!GGIKK!!i9;O;O;Q!RR	Ss   B
B 	C1AC,,C1c                 z    |r+ t        | j                  |      |       d| j                  dS d| j                  dS )a  
        Generic implementation of the absent state for the OneView resources.

        It checks if the resource needs to be removed.

        :arg dict resource: Resource to delete.
        :arg str method: Function of the OneView client that will be called for resource deletion.
            Usually delete or remove.
        :return: A dictionary with the expected arguments for the AnsibleModule.exit_json
        T)r   r:   F)getattrresource_clientMSG_DELETEDMSG_ALREADY_ABSENT)rA   resourcemethods      r   resource_absentz!OneViewModuleBase.resource_absent*  s@     1GD((&1(;#D,<,<==$T-D-DEEr   c                 L    | j                   j                  d|      }|r|d   S dS )z
        Generic get by name implementation.

        :arg str name: Resource name to search for.

        :return: The resource found or None.
        namer   N)r   get_by)rA   r   r   s      r   get_by_namezOneViewModuleBase.get_by_name<  s-     %%,,VT:"vay,,r   c                    d}d| j                   v r(| j                   j                  d      | j                   d<   |s5 t        | j                  |      | j                         }| j                  }d}ns|j                         }|j                  | j                          | j                  ||      r| j                  }n)| j                  j                  |      }d}| j                  }t        ||||i      S )a  
        Generic implementation of the present state for the OneView resources.

        It checks if the resource needs to be created or updated.

        :arg dict resource: Resource to create or update.
        :arg str fact_name: Name of the fact returned to the Ansible.
        :arg str create_method: Function of the OneView client that will be called for resource creation.
            Usually create or add.
        :return: A dictionary with the expected arguments for the AnsibleModule.exit_json
        FnewNamer   T)r:   r   ansible_facts)rB   r   r   r   MSG_CREATEDr   r   compareMSG_ALREADY_PRESENTMSG_UPDATEDr=   )rA   r   	fact_namecreate_methodr   r:   merged_datas          r   resource_presentz"OneViewModuleBase.resource_presentG  s     		! $		i 8DIIfCwt33]CDIINH""CG #--/Ktyy)||Hk2..//66{C&&$h/
 	
r   c                     |g }|d   |   }t        dd|      }|d   t        |d         t        |      k7  r: | j                  j                  |d   fi ||d   |<   d|d<   | j                  |d	<   |S )
a  
        Generic implementation of the scopes update PATCH for the OneView resources.
        It checks if the resource needs to be updated with the current scopes.
        This method is meant to be run after ensuring the present state.
        :arg dict state: Dict containing the data from the last state results in the resource.
            It needs to have the 'msg', 'changed', and 'ansible_facts' entries.
        :arg str fact_name: Name of the fact returned to the Ansible.
        :arg list scope_uris: List with all the scope URIs to be added to the resource.
        :return: A dictionary with the expected arguments for the AnsibleModule.exit_json
        r   replacez
/scopeUris)	operationrX   r   	scopeUrisuriTr   r:   )r=   setr   patchr   )rA   rg   r   
scope_urisr   operation_datas         r   resource_scopes_setz%OneViewModuleBase.resource_scopes_setn  s     J))4	JWK (C0E,F#j/,Y0J0D0D0J0J8TY?0m^l0mE/"9-#E)++E%Lr   c                    |}|}dj                  ||      }|r!|s| j                  j                  d|z          y|D ]q  }||vr?||   | j                  j                  | j                  j                  |      |z           y||   s||   sRt	        ||   t
              rR| j                  ||   ||         r~| j                  j                  | j                  j                  |      |z           yt	        ||   t              rR| j                  ||   ||         r| j                  j                  | j                  j                  |      |z           yt        ||         t        ||         k7  s;| j                  j                  | j                  j                  |      |z           y |j                         D ]E  }||vs||   | j                  j                  | j                  j                  |      |z           y y)a?  
        Recursively compares dictionary contents equivalence, ignoring types and elements order.
        Particularities of the comparison:
            - Inexistent key = None
            - These values are considered equal: None, empty, False
            - Lists are compared value by value after a sort, if they have same size.
            - Each element is converted to str before the comparison.
        :arg dict first_resource: first dictionary
        :arg dict second_resource: second dictionary
        :return: bool: True when equal, False when different.
         resource1 = {0}, resource2 = {1}zresource1 and not resource2. FT)formatrk   logMSG_DIFF_AT_KEYr   r   r   r   compare_listr5   keys)rA   first_resourcesecond_resource	resource1	resource2debug_resourcesr!   s          r   r   zOneViewModuleBase.compare  s    #	#	<CCIyY YKKOO;oMN  	C)#S>-KKOOD$8$8$?$?$D$VW s^IcNIcNG4||IcNIcNCKKOOD$8$8$?$?$D$VW IcND1((33HKKOOD$8$8$?$?$D$VW #IcN37I)TW.7YY 4 4 ; ;C @? RS+	0 >># 	!C)#S>-KKOOD$8$8$?$?$D$VW 	! r   c                    |}|}dj                  ||      }|s| j                  j                  d|z          yt        |      t        |      k7  r| j                  j                  d|z          yt	        |t
              }t	        |t
              }t        |      D ]  \  }}t        |t              r6| j                  |||         r,| j                  j                  d|z           yt        |t              r6| j                  |||         rr| j                  j                  d|z           yt        |      t        ||         k7  s| j                  j                  d|z           y y	)
a  
        Recursively compares lists contents equivalence, ignoring types and element orders.
        Lists with same size are compared value by value after a sort,
        each element is converted to str before the comparison.
        :arg list first_resource: first list
        :arg list second_resource: second list
        :return: True when equal; False when different.
        r   zresource 2 is null. Fz!resources have different length. )r!   zresources are different. zlists are different. zvalues are different. T)r   rk   r   lensortedr0   	enumerater   r   r   r   r   r5   )rA   r   r   r   r   r   r#   vals           r   r   zOneViewModuleBase.compare_list  s8    #	#	<CCIyY KKOO2_DEy>S^+KKOO?/QR9+6	9+6		* 	FAs#w'||C16KKOO$?/$QR C&((il;KKOO$;o$MN #C(,>y|,LL 8? JK	  r   )NFF)delete)create)rC   rD   rE   r   r   r   r   r   r   r=   rr   rs   r   r@   rj   rl   rm   abcabstractmethodr   r   r   r   r   r   r   r   rG   r   r   rW   rW      s    2K2K2K869O 5!5!5.e$ $% 0 "&Dfd4S!TO;2h
] 		 	S2F$	-%
N.6p+r   rW   rK   )'
__future__r   r   r   rY   __metaclass__r   r   r,   osr   r{   hpOneView.oneview_clientr   ry   ImportErrorr   ansible.module_utilsr   ansible.module_utils.basicr   r	   +ansible.module_utils.common.text.convertersr   /ansible.module_utils.common._collections_compatr   r   r)   r0   r5   r?   r7   rI   rQ   rU   add_metaclassABCMetaobjectrW   rG   r   r   <module>r      s    C B 
   	  6O
 % J A C,%'P /Y /6%3 %	4 		$: 	 3;;n n  n  .)..0Os   B* *CC