
    gW                        d dl Z d dlZd dlZd dlmZ d dlmZmZmZm	Z	m
Z
 d dlmc mZ d dlmZmZmZmZmZmZmZmZmZ d dlmZ d dlmZ d dlmZ d dlm Z  d d	l!m"Z"m#Z# d d
l$m%Z% d dl&m'Z' dZ(dZ)dZ*dZ+dZ,dZ-dZ.dZ/dZ0dZ1dZ2dZ3dddddZ4 ejj                         Z6 ejn                   ejp                  e9            Z: edddg      Z; G d dejx                        Z= G d d e%j|                        Z?d!e@fd"ZA	 d>d#ed$eeBef   d%eeBef   d&eCd'eCd(dfd)ZD	 	 d?d#ed*eeBef   d+eeBef   d&eCd'eCd(e
eeCf   fd,ZEd-ej                  d(ej                  fd.ZHd#efd/ZId#ed(ee   fd0ZJd#ed1eBd(eeBef   fd2ZKd3eeBeBf   d4eeBeBf   d(eLfd5ZM	 d@d6eeBef   d7eBd8eBde	eB   d(eeLeeBef   f   f
d9ZN	 	 dAd*eeBef   d:e	eB   de	eB   d(dfd;ZOd#ed<eeBef   d(ee;   fd=ZPy)B    N)
namedtuple)AnyDictListOptionalTuple)	
data_typesevent_logger
exceptionshttpmessagessecret_managersystemutilversion)_enabled_services)_is_attached)UAConfig)ATTACH_FAIL_DATE_FORMAT)attachment_data_filemachine_id_file)serviceclient)get_user_or_root_log_file_pathz/v1/context/machines/tokenz3/v1/contracts/{contract}/context/machines/{machine}z/v1/resourcesz3/v1/resources/{resource}/context/machines/{machine}z/v1/clouds/{cloud_type}/tokenz3/v1/contracts/{contract}/machine-activity/{machine}z/v1/contractz/v1/magic-attachz?/v1/contracts/{contract}/context/machines/{machine}/guest-token            )series_overridesseriescloudvariantEnableByDefaultServicenamer!   c                   
   e Zd Z ej                  dej
                  d       ej                  dej
                  d       ej                  dej
                  d       ej                  dej
                  d       ej                  dej
                  d       ej                  dej
                  d       ej                  d	ej
                  d       ej                  d
ej
                  d       ej                  dej
                  d       ej                  dej
                  d       ej                  dej
                  d       ej                  dej
                  d       ej                  dej
                  d       ej                  dej
                  d      gZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddee   dee   dee   dee   dee   dee   d	ee   d
ee   dee   dee   dee   dee   dee   dee   fdZ	y)CPUTypeDatacpuinfo_cpuF)requiredcpuinfo_cpu_architecturecpuinfo_cpu_familycpuinfo_cpu_implementercpuinfo_cpu_partcpuinfo_cpu_revisioncpuinfo_cpu_variantcpuinfo_modelcpuinfo_model_namecpuinfo_steppingcpuinfo_vendor_id"sys_firmware_devicetree_base_modelsysinfo_modelsysinfo_typeNc                     || _         || _        || _        || _        || _        || _        || _        || _        |	| _        |
| _	        || _
        || _        || _        || _        y Nr&   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   )selfr&   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   s                  3/usr/lib/python3/dist-packages/uaclient/contract.py__init__zCPUTypeData.__init__z   sy    " '(@%"4'>$ 0$8!#6 *"4 0!2. 	/ +(    )NNNNNNNNNNNNNN)
__name__
__module____qualname__r	   FieldStringDataValuefieldsr   strr:    r;   r9   r%   r%   F   s   
:55	
 	
&&&	

 	
 *"<"<u	
 	
%&&	

 	

 : :U	
 	
"J$>$>	
 	
!:#=#=	
 	
Z77%	
 	
 *"<"<u	
 	

 : :U	
 	
!;!;e	
 	
0&&	

 	
Z77%	
 	
J66	
]1Fj &*26,015*..2-1'+,0*.+/<@'+&* )c] ) #+3- ) %SM	 )
 "*# ) #3- ) 'sm ) &c] )  } ) %SM ) #3- ) $C= ) -5SM )  } ) sm )r;   r%   c                       e Zd ZdZ	 ddee   ddf fdZ ej                  e	j                  g d      	 dd       Zdeeef   fd	Zd
edeeef   fdZ ej                  e	j                  g d      dedeeef   fd       Z	 ddededee   deeef   fdZd Zdedeeef   fdZdeeef   fdZdefdZ	 ddededee   deeef   fdZ	 ddededee   defdZdedededefdZd Z xZS )UAContractClientcontract_urlNcfgreturnc                 X    t         |   |       t        j                         | _        y )NrG   )superr:   mtfget_machine_token_filemachine_token_file)r8   rG   	__class__s     r9   r:   zUAContractClient.__init__   s&     	S!"%"<"<">r;   )r   r   r   )retry_sleepsc                 <   |st        j                  | j                        }| j                         }|j	                  ddj                  |      i       | j                         }|j                         |d<   ||d}t        |      }| j                  t        ||      }|j                  dk(  rt        j                         |j                  dk(  rt        |       |j                  dk7  r0t        j                  t        |j                  |j                   	      |j"                  }	t$        j&                  j)                  |	j+                  d
d             |	j+                  dg       D ]1  }
t$        j&                  j)                  |
j+                  dd             3 |	S )a}  Requests machine attach to the provided machine_id.

        @param contract_token: Token string providing authentication to
            ContractBearer service endpoint.
        @param machine_id: Optional unique system machine id. When absent,
            contents of /etc/machine-id will be used.

        @return: Dict of the JSON response containing the machine-token.
        Authorization	Bearer {}lastAttachment	machineIdactivityInfo)dataheaders  i     urlcodebodymachineToken resourceTokenstoken)r   get_machine_idrG   rY   updateformat_get_activity_info	isoformat_support_old_machine_inforequest_urlAPI_V1_ADD_CONTRACT_MACHINEr^   r   AttachInvalidTokenError_raise_attach_forbidden_messageContractAPIErrorr_   	json_dictr   secrets
add_secretget)r8   contract_tokenattachment_dt
machine_idrY   activity_inforX   backcompat_dataresponseresponse_jsonrc   s              r9   add_contract_machinez%UAContractClient.add_contract_machine   sl    ..txx8J,,.););N)KLM//1*7*A*A*C&''G3D9##'ow $ 
 ==C4466]]c!+H5==C--/]]]] 
 !**))nb1	
 #&&'7< 	FE""--eii.DE	Fr;   c                    | j                         }| j                  t        |d   |d   |d   |d   d      }|j                  dk7  r0t	        j
                  t        |j                  |j                        |j                  S )	z=Requests list of entitlements available to this machine type.architecturer   kernelvirtr|   r   r}   r~   )query_paramsr[   r\   )rg   rj   API_V1_AVAILABLE_RESOURCESr^   r   rn   r_   ro   )r8   rv   rx   s      r9   available_resourcesz$UAContractClient.available_resources   s    //1##& -n ='1'1%f-	 $ 
 ==C--.]]]] 
 !!!r;   rs   c                 *   | j                         }|j                  ddj                  |      i       | j                  t        |      }|j
                  dk7  r0t        j                  t        |j
                  |j                        |j                  S )NrR   rS   rY   r[   r\   )
rY   re   rf   rj   API_V1_GET_CONTRACT_USING_TOKENr^   r   rn   r_   ro   )r8   rs   rY   rx   s       r9   get_contract_using_tokenz)UAContractClient.get_contract_using_token   s    ,,.););N)KLM##+W $ 
 ==C--3]]]] 
 !!!r;   
cloud_typerX   c                   | j                  t        j                  |      |      }|j                  dk7  ry|j                  j                  dd      }|r+t        j                  |       t        j                  |      t        j                  t        |j                  |j                        |j                  }t        j                  j                  |j                  dd             |S )	zRequests contract token for auto-attach images for Pro clouds.

        @param instance: AutoAttachCloudInstance for the cloud.

        @return: Dict of the JSON response containing the contract-token.
        )r   )rX   r[   messagera   )	error_msgr\   contractToken)rj   ,API_V1_GET_CONTRACT_TOKEN_FOR_CLOUD_INSTANCErf   r^   ro   rr   LOGdebugr   InvalidProImagern   r_   r   rp   rq   )r8   r   rX   rx   msgry   s         r9   %get_contract_token_for_cloud_instancez6UAContractClient.get_contract_token_for_cloud_instance   s     ##8??% @  	 $ 
 ==C$$((B7C		# 003??--@]]]]  !**))or2	
 r;   machine_tokenresourceru   c                    |st        j                  | j                        }| j                         }|j	                  ddj                  |      i       t        j                  ||      }| j                  ||      }|j                  dk7  r0t        j                  t        |j                  |j                        |j                  j                  d      r|j                  d   |j                  d<   |j                  }|j                  dg       D ]1  }t        j                  j!                  |j                  d	d
             3 |S )a  Requests machine access context for a given resource

        @param machine_token: The authentication token needed to talk to
            this contract service endpoint.
        @param resource: Entitlement name.
        @param machine_id: Optional unique system machine id. When absent,
            contents of /etc/machine-id will be used.

        @return: Dict of the JSON response containing entitlement accessInfo.
        rR   rS   )r   machiner   r[   r\   expiresrb   rc   ra   )r   rd   rG   rY   re   rf   "API_V1_GET_RESOURCE_MACHINE_ACCESSrj   r^   r   rn   r_   rr   ro   r   rp   rq   )	r8   r   r   ru   rY   r]   rx   ry   rc   s	            r9   get_resource_machine_accessz,UAContractClient.get_resource_machine_access  s#     ..txx8J,,.););M)JKL077z 8 
 ##C#9==C--6]]]] 
 	*,4,<,<Y,GHy) **"&&'7< 	FE""--eii.DE	Fr;   c                    | j                   j                  }| j                   j                  j                  d      }t	        j
                  | j                        }| j                         }t        j                  ||      }| j                         }|j                  ddj                  |      i       | j                  |||      }|j                  dk7  r,t        j                  ||j                  |j                         |j"                  rA| j                   j                  }|j"                  |d<   | j                   j%                  |       y	y	)
zReport current activity token and enabled services.

        This will report to the contracts backend all the current
        enabled services in the system.
        r`   contractr   rR   rS   )rY   rX   r[   r\   rW   N)rN   contract_idr   rr   r   rd   rG   rg   API_V1_UPDATE_ACTIVITY_TOKENrf   rY   re   rj   r^   r   rn   r_   ro   write)r8   r   r   ru   request_datar]   rY   rx   s           r9   update_activity_tokenz&UAContractClient.update_activity_token;  s'    --99//==AA
 **4884
..0*11 * 2 
 ,,.););M)JKL##C|#L==C--hmm(--   33AAM -5,>,>M.)##))-8 r;   magic_tokenc                 .   | j                         }|j                  ddj                  |      i       | j                  t        |      }|j
                  dk(  rt        j                         |j
                  dk(  rt        j                         |j
                  dk7  r0t        j                  t        |j
                  |j                        |j                  }g d}|D ]1  }t        j                  j                  |j                  |d	             3 |S )
zRequest magic attach token info.

        When the magic token is registered, it will contain new fields
        that will allow us to know that the attach process can proceed
        rR   rS   r   rZ     r[   r\   rc   userCoder   ra   )rY   re   rf   rj   "API_V1_GET_MAGIC_ATTACH_TOKEN_INFOr^   r   MagicAttachTokenErrorMagicAttachUnavailablern   r_   ro   r   rp   rq   rr   )r8   r   rY   rx   ry   secret_fieldsfields          r9   get_magic_attach_token_infoz,UAContractClient.get_magic_attach_token_infoc  s     ,,.););K)HIJ##. $ 
 ==C2244==C3355==C--6]]]] 
 !**>" 	LE""--m.?.?r.JK	Lr;   c                    | j                         }| j                  t        |d      }|j                  dk(  rt	        j
                         |j                  dk7  r0t	        j                  t        |j                  |j                        |j                  }g d}|D ]1  }t        j                  j                  |j                  |d             3 |S )z)Create a magic attach token for the user.POSTrY   methodr   r[   r\   r   ra   )rY   rj   API_V1_NEW_MAGIC_ATTACHr^   r   r   rn   r_   ro   r   rp   rq   rr   )r8   rY   rx   ry   r   r   s         r9   new_magic_attach_tokenz'UAContractClient.new_magic_attach_token  s    ,,.### $ 
 ==C3355==C--+]]]] 
 !**>" 	LE""--m.?.?r.JK	Lr;   c                    | j                         }|j                  ddj                  |      i       | j                  t        |d      }|j
                  dk(  rt        j                         |j
                  dk(  rt        j                         |j
                  dk(  rt        j                         |j
                  dk7  r0t        j                  t        |j
                  |j                  	      y
)z)Revoke a magic attach token for the user.rR   rS   DELETEr     rZ   r   r[   r\   N)rY   re   rf   rj   API_V1_REVOKE_MAGIC_ATTACHr^   r    MagicAttachTokenAlreadyActivatedr   r   rn   r_   )r8   r   rY   rx   s       r9   revoke_magic_attach_tokenz*UAContractClient.revoke_magic_attach_token  s    ,,.););K)HIJ##& $ 
 ==C==??==C2244==C3355==C--.]]]]   r;   r   c           
      >   |st        j                  | j                        }| j                         }|j	                  ddj                  |      i       t        j                  ||      }| j                         }| j                  |d||d   |d   |d   |d   d	
      }|j                  dk7  r,t        j                  ||j                  |j                        |j                  j                  d      r|j                  d   |j                  d<   |j                  S )a|  Get the updated machine token from the contract server.

        @param machine_token: The machine token needed to talk to
            this contract service endpoint.
        @param contract_id: Unique contract id provided by contract service
        @param machine_id: Optional unique system machine id. When absent,
            contents of /etc/machine-id will be used.
        rR   rS   r   GETr|   r   r}   r~   r   )r   rY   r   r[   r\   r   )r   rd   rG   rY   re   rf   API_V1_GET_CONTRACT_MACHINErg   rj   r^   r   rn   r_   rr   ro   )r8   r   r   ru   rY   r]   rv   rx   s           r9   get_contract_machinez%UAContractClient.get_contract_machine  s    ..txx8J,,.););M)JKL)00  1 
 //1## -n ='1'1%f-		 $ 

 ==C--hmm(--  	*,4,<,<Y,GHy)!!!r;   c                 8   |st        j                  | j                        }| j                         }|j	                  ddj                  |      i       || j                         d}t        |      }t        j                  ||      }| j                  ||d|      }|j                  dk7  r,t        j                  ||j                  |j                        |j                  j                  d	      r|j                  d	   |j                  d	<   |j                  S )
a  Request machine token refresh from contract server.

        @param machine_token: The machine token needed to talk to
            this contract service endpoint.
        @param contract_id: Unique contract id provided by contract service.
        @param machine_id: Optional unique system machine id. When absent,
            contents of /etc/machine-id will be used.

        @return: Dict of the JSON response containing refreshed machine-token
        rR   rS   rU   r   r   )rY   r   rX   r[   r\   r   )r   rd   rG   rY   re   rf   rg   ri   API_V1_UPDATE_CONTRACT_MACHINErj   r^   r   rn   r_   rr   ro   )	r8   r   r   ru   rY   rX   rw   r]   rx   s	            r9   update_contract_machinez(UAContractClient.update_contract_machine  s     ..txx8J,,.););M)JKL# 335
 4D9,33 * 4 
 ##o $ 
 ==C--hmm(--  	*,4,<,<Y,GHy)!!!r;   c                    | j                         }|j                  ddj                  |      i       t        j                  ||      }| j	                  ||d      }|j
                  dk(  rt        j                  d      |j
                  d	k7  r,t        j                  ||j
                  |j                  
      |j                  S )a  Request guest token associated with this machine's contract
        @param machine_token: The machine token needed to talk to
            this contract service endpoint.
        @param contract_id: Unique contract id provided by contract service
        @param machine_id: Unique machine id that was registered with the pro
            backend on attach.
        @return: Dict of the JSON response containing the guest token
        rR   rS   r   r   r   r   get_guest_token)feature_namer[   r\   )rY   re   rf   API_V1_GET_GUEST_TOKENrj   r^   r    FeatureNotSupportedOldTokenErrorrn   r_   ro   )r8   r   r   ru   rY   r]   rx   s          r9   r   z UAContractClient.get_guest_token   s     ,,.););M)JKL$++  , 
 ##C#G==C ==.  ]]c!--]]]] 
 !!!r;   c                    t        j                         }t        j                         j                  t        j                         j
                  t        j                         j                  t        j                         t        j                         t        j                         t        j                         t        |j                  |j                  |j                  |j                   |j"                  |j$                  |j&                  |j(                  |j*                  |j,                  |j.                  |j0                  |j2                  |j4                        j7                  d      d}t9        | j:                        j<                  rt?        | j:                        j@                  }tC        jD                         }| jF                  jH                  xs t        jJ                  | j:                        | jF                  jL                  |D cg c]  }|jN                   c}|D ci c]%  }|jP                  r|jN                  |jR                  ' c}|r|jT                  jW                         ndd}ni }i ||S c c}w c c}w )z9Return a dict of activity info data for contract requestsr7   F)	keep_none)distributionr}   r   r|   desktopr~   clientVersioncpu_typeN)
activityIDactivityToken	resourcesresourceVariantsrT   ),r   get_cpu_infoget_release_infor   get_kernel_infouname_releaser   get_dpkg_arch
is_desktopget_virt_typer   get_versionr%   r&   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   to_dictr   rG   is_attachedr   enabled_servicesr   readrN   activity_idrd   activity_tokenr#   variant_enabledvariant_nameattached_atrh   )r8   cpuinfomachine_infor   attachment_dataservicerv   s          r9   rg   z#UAContractClient._get_activity_info#  s    %%'"335BB,,.<<--/66"002((*((*$002##//)0)I)I#*#=#=(/(G(G!(!9!9%,%A%A$+$?$?%33#*#=#=!(!9!9")";";3:3]3]%33$11 gg&/
4 !--0:KK2779O"55AA 3((2!%!8!8!G!G:JKwgllK $4%.. LL'"6"66% ' $//99;M" M


 	
 L%s   I>)*J
r6   )r<   r=   r>   cfg_url_base_attrr   r   r:   r   retrysockettimeoutrz   r   rB   r   r   r   r   r   r   r   r   r   r   r   r   rg   __classcell__)rO   s   @r9   rE   rE      s   & #'?h? 
? TZZY78<( 8(T"T#s(^ "("s "tCH~ " TZZY7 (,S#X 8H %)	$$ $ SM	$
 
c3h$L&9Ps tCH~ 8S#X .S 6 %)	)")" )" SM	)"
 
c3h)"^ %)	&"&" &" SM	&"
 
&"P!"!" !" 	!"
 
!"F7
r;   rE   request_bodyc           	         | j                  di       }| j                  d      ||j                  d      |j                  d      |j                  d      |j                  d      dt        j                         j                  dd	S )
a?  
    Transforms a request_body that has the new activity_info into a body that
    includes both old and new forms of machineInfo/activityInfo

    This is necessary because there may be old ua-airgapped contract
    servers deployed that we need to support.
    This function is used for attach and refresh calls.
    rW   rV   r|   r   r}   r   Linux)r   r}   r   typerelease)rV   rW   r|   os)rr   r   r   r   )r   rv   s     r9   ri   ri   ]  s     !$$^R8M "%%k2%%)).9)--n=#''1#''1 ..088
	 r;   rG   past_entitlementsnew_entitlementsallow_enabler   rH   c                    ddl m} d}g }g } ||       D ]I  }		 ||	   }
g }	 t        | |j	                  |	i       |
||      \  }}|s2|s5t
        j                  |	       K t
        j                  |       t        |      dkD  ret        j                   t#        ||      D 	cg c]9  \  }	}|	t$        j&                  j)                  t+        |      t-               	      f; c}}	
      |r4t        j.                  |D 	cg c]  }	|	t$        j0                  f c}	
      y# t        $ r Y w xY w# t        j                  $ rJ}t        j                  |       d}|j                  |	       t        j                  d|	|
       Y d}~sd}~wt        $ rY}t        j                  |       |j                  |       |j                  |	       t        j                  d|	|
       Y d}~d}~ww xY wc c}}	w c c}	w )a  Iterate over all entitlements in new_entitlement and apply any delta
    found according to past_entitlements.

    :param cfg: UAConfig instance
    :param past_entitlements: dict containing the last valid information
        regarding service entitlements.
    :param new_entitlements: dict containing the current information regarding
        service entitlements.
    :param allow_enable: Boolean set True if allowed to perform the enable
        operation. When False, a message will be logged to inform the user
        about the recommended enabled service.
    :param series_overrides: Boolean set True if series overrides should be
        applied to the new_access dict.
    r   )entitlements_enable_orderF)rG   orig_access
new_accessr   r   Tz+Failed to process contract delta for %s: %rNz5Unexpected error processing contract delta for %s: %r)r   log_path)failed_services)uaclient.entitlementsr   KeyErrorprocess_entitlement_deltarr   eventservice_processedr   UbuntuProErrorr   	exceptionappenderror	Exceptionservices_failedlenAttachFailureUnknownErrorzipr   UNEXPECTED_ERRORrf   rB   r   AttachFailureDefaultServices!E_ATTACH_FAILURE_DEFAULT_SERVICES)rG   r   r   r   r   r   delta_errorunexpected_errorsr   r#   new_entitlementdeltasservice_enableder   s                  r9   process_entitlements_deltar  x  s   * @K O)#. %.	.t4O 	.&?-11$;*)!1'#FO8 6''-K%.L 
/*
!22 (+?<M'N	 $D) --44"%i.!?!A 5 	
 	
 
55 , xAAB
 	
 
c  		 (( 	MM!K""4(II= 
  	MM!$$Q'""4(MMG 		"	sA   D #D0">G0
>G6 	D-,D-0G-?FG-AG((G-r   r   c                 (   ddl m} |rt        |       t        j                  ||      }d}|r|j                  di       j                  d      }|s!|j                  di       j                  d      }|st        j                  ||      |j                  di       j                  di       j                  d	d
      }		  || ||	      }
|
j                  |||      }||fS # t        j                  $ r}t        j                  d|       |d}~ww xY w)a,  Process a entitlement access dictionary deltas if they exist.

    :param cfg: UAConfig instance
    :param orig_access: Dict with original entitlement access details before
        contract refresh deltas
    :param new_access: Dict with updated entitlement access details after
        contract refresh
    :param allow_enable: Boolean set True if allowed to perform the enable
        operation. When False, a message will be logged to inform the user
        about the recommended enabled service.
    :param series_overrides: Boolean set True if series overrides should be
        applied to the new_access dict.

    :raise UbuntuProError: on failure to process deltas.
    :return: A tuple containing a dict of processed deltas and a
             boolean indicating if the service was fully processed
    r   entitlement_factoryFentitlementr   )orignewentitlementsobligationsuse_selectorra   rG   r#   r!   z3Skipping entitlement deltas for "%s". No such classNr   )r   r  apply_contract_overridesr   get_dict_deltasrr   r    InvalidContractDeltasServiceTypeEntitlementNotFoundErrorr   r   process_contract_deltas)rG   r   r   r   r   r  r  retr#   r!   r  excs               r9   r   r     s   0 : ,!!+z:F
C}b155f=::mR044V<D== j 
 NN>2.S#S$ 	

	-K 11l 2 
 3; 22 	IIEt I		s   >C! !D4DDrx   c                    | j                   j                  d      }|r|d   }|d   }|dk(  rB|d   j                  t              }t	        j
                  |||d   j                  d            |dk(  rB|d   j                  t              }t	        j                  |||d   j                  d      	      |d
k(  rt	        j                  |      t	        j                         )Ninfo
contractIdreasonzno-longer-effectivetimez%m-%d-%Y)r   datecontract_expiry_dateznot-effective-yet)r   r&  contract_effective_dateznever-effective)r   )	ro   rr   strftimer   r   AttachForbiddenExpiredAttachForbiddenNotYetAttachForbiddenNeverAttachExpiredToken)rx   r"  r   r$  r&  s        r9   rm   rm     s     !!&)D<(h**<(()@AD33'%)&\%:%::%F	  **<(()@AD22'(,V(=(=j(I	  ((11kJJ

'
'
))r;   c                    t        j                  |       }|j                         }|j                  }|d   }|d   d   d   }t	        |       }|j                  ||      }|j                  |       t        j                  j                          |j                  di       j                  dt        j                  |             }t        j                  |       t        | ||j                         d	       y
)zRequest contract refresh from ua-contracts service.

    :raise UbuntuProError: on failure to update contract or error processing
        contract deltas
    :raise ConnectivityError: On failure during a connection
    r`   machineTokenInfocontractInfoidrJ   )r   r   rV   Fr  N)rL   rM   r  r   rE   r   r   r   rd   cache_clearrr   r   r  )	rG   rN   orig_entitlements
orig_tokenr   r   contract_clientrespru   s	            r9   refreshr7  .  s     33C8*779#11J~.M/0@FK&3/O22# 3 D T"
%%',b155V**3/J *%'')	r;   c                 \    t        |       }|j                         }|j                  dg       S )zDQuery available resources from the contract server for this machine.r   )rE   r   rr   )rG   clientr   s      r9   get_available_resourcesr:  O  s+    c"F**,I==b))r;   rc   c                 :    t        |       }|j                  |      S )z/Query contract information for a specific token)rE   r   )rG   rc   r9  s      r9   get_contract_informationr<  V  s    c"F**511r;   override_selectorselector_valuesc                 ~    d}| j                         D ]'  \  }}||f|j                         vr y|t        |   z  }) |S )Nr   )itemsOVERRIDE_SELECTOR_WEIGHTS)r=  r>  override_weightselectorvalues        r9   _get_override_weightrE  \  sV     O,224 ?%eO$9$9$;;4X>>?
 r;   r  series_namer   c                     i }||d}|r||d<   | j                  di       j                  |i       }|r||t        d   <   t        j                  | j	                  dg             }|D ]%  }t        |j                  d      |      }	|	s!|||	<   ' |S )N)r   r    r!   r   r   	overridesrC  )poprA  copydeepcopyrr   rE  )
r  rF  r   r!   rH  r>  r   general_overridesoverrideweights
             r9   _select_overridesrO  h  s     I!,zBO%,	""x488bI 	+,>?@ kook2&FG% )%LL$o
  (If) r;   r   c                    ddl m} t        t        | t              d| v g      st        dj                  |             |t        j                         j                  n|} |       \  }}| j                  di       }t        ||||      }t        |j                               D ][  \  }	}
|
j                         D ]C  \  }}| d   j                  |      }t        |t              r|j                  |       <|| d   |<   E ] y)a  Apply series-specific overrides to an entitlement dict.

    This function mutates orig_access dict by applying any series-overrides to
    the top-level keys under 'entitlement'. The series-overrides are sparse
    and intended to supplement existing top-level dict values. So, sub-keys
    under the top-level directives, obligations and affordance sub-key values
    will be preserved if unspecified in series-overrides.

    To more clearly indicate that orig_access in memory has already had
    the overrides applied, the 'series' key is also removed from the
    orig_access dict.

    :param orig_access: Dict with original entitlement access details
    r   )get_cloud_typer  z?Expected entitlement access dict. Missing "entitlement" key: {}N)uaclient.clouds.identityrQ  all
isinstancedictRuntimeErrorrf   r   r   r   rr   rO  sortedr@  re   )r   r   r!   rQ  rF  r   _orig_entitlementrH  _weightoverrides_to_applykeyrD  currents                 r9   r  r    s
   & 8
;-}/KLM&%
 	
 -3N!((  #$MJ"}b9!+z7I (.ioo.?'@ 	8##,224 	8JC!-044S9G'4( u% 38M*3/	8	8r;   r  c                    ddl m} g }|j                         D ]  \  }}|j                  di       j                  dd      }	  || ||      }|j                  di       j                  di       }|j                  d      }	|j                  ||	      sz|j                         \  }
}|
s|j                  t        ||	              |S # t        j
                  $ r Y w xY w)
Nr   r  r  r  ra   r  r  resourceToken)r#   r!   )
r   r  r@  rr   r   r  _should_enable_by_default
can_enabler   r"   )rG   r  r  enable_by_default_servicesent_name	ent_valuer!   entr  r_  ra  rX  s               r9   get_enabled_by_default_servicesrf    s     :!#+113 )--r266~rJ	%#HgNC  mmM26::="M!o6((mDNN,MJ*11*% '* &%! 22 		s   C		CC)T)FTr6   )NN)QrJ  loggingr   collectionsr   typingr   r   r   r   r   uaclient.files.machine_tokenfilesr   rL   uaclientr	   r
   r   r   r   r   r   r   r   -uaclient.api.u.pro.status.enabled_services.v1r   (uaclient.api.u.pro.status.is_attached.v1r   uaclient.configr   uaclient.defaultsr   uaclient.files.state_filesr   r   uaclient.httpr   uaclient.logr   rk   r   r   r   r   r   r   r   r   r   r   r   rA  get_event_loggerr   	getLoggerreplace_top_level_logger_namer<   r   r"   
DataObjectr%   UAServiceClientrE   rU  ri   rB   boolr  r   HTTPResponseNamedMessagerm   r7  r:  r<  intrE  rO  r  rf  rC   r;   r9   <module>r}     sJ      " 3 3 * *
 
 
 L A $ 5 L ' 7 ; 9  :  - 9 # 0O ,9  #1 %7 ", /  F 
 	  	&%%'g:::8DE $vy1 
T)*'' T)n}
}44 }
@D @ "W
	W
CH~W
 38nW
 	W

 W
 
W
| !<	<c3h< S#X< 	<
 < 4:<~***: B* *d4j *2( 23 24S> 2	CH~	8<S#X		  "	c3h  c]	
 
#tCH~
> !!.8c3h.8SM.8 c].8 
	.8b&	&!%c3h&	
 !&r;   