HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //usr/lib/python3/dist-packages/uaclient/__pycache__/contract.cpython-310.pyc
o

nHJe6y�@s�ddlZddlZddlZddlZddlmZmZmZmZm	Z	ddl
mZmZm
Z
mZmZmZmZmZddlmZddlmZddlmZddlmZmZmZddlmZdd	lm Z d
Z!dZ"dZ#dZ$d
Z%dZ&dZ'dZ(dZ)dZ*dZ+ddddd�Z,e�-�Z.e�/e�0e1��Z2ej3Gdd�dej4��Z5Gdd�de j6�Z7de8fdd�Z9	dGded ee:efd!ee:efd"e;d#e;d$dfd%d&�Z<	'	dHded(ee:efd)ee:efd"e;d#e;d$e	ee;ffd*d+�Z=d,ej>d$ej?fd-d.�Z@d/d0�ZAded$eefd1d2�ZBded3e:d$ee:effd4d5�ZCded$e;fd6d7�ZDd8ee:e:fd9ee:e:fd$eEfd:d;�ZF	dId<ee:efd=e:d>e:d?ee:d$eeEee:efff
d@dA�ZG		dJd(ee:efdBee:d?ee:d$dfdCdD�ZHded$e	e5eEffdEdF�ZIdS)K�N)�Any�Dict�List�Optional�Tuple)�clouds�event_logger�
exceptions�http�messages�system�util�version)�_enabled_services)�_is_attached)�UAConfig)�ATTACH_FAIL_DATE_FORMAT�!CONTRACT_EXPIRY_GRACE_PERIOD_DAYS�CONTRACT_EXPIRY_PENDING_DAYS)�attachment_data_file)�
serviceclientz/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-attach����)�series_overrides�series�cloud�variantc@s eZdZdZdZdZdZdZdS)�ContractExpiryStatusrrrrrN)�__name__�
__module__�__qualname__�NONE�ACTIVE�ACTIVE_EXPIRED_SOON�EXPIRED_GRACE_PERIOD�EXPIRED�r(r(�3/usr/lib/python3/dist-packages/uaclient/contract.pyr>src
@sNeZdZdZejejgd�d�	d'dd��Zde	e
effdd	�Zd
e
de	e
effdd�Z
ejejgd�d�d
ejfdd��Z		d(de
de
dee
dede	e
eff
dd�Zdd�Zde
de	e
effdd�Zde	e
effdd�Zde
fdd�Z	d'de
d e
dee
de	e
effd!d"�Z	d'de
d e
dee
de	fd#d$�Zd%d&�ZdS))�UAContractClient�contract_url)rrr)�retry_sleepsNc	Cs�|st�|j�}|��}|�dd�|�i�|��}|��|d<||d�}t|�}|j	t
||d�}|jdkr:t�
��|jdkrCt|�|jdkrRtjt
|j|jd	��|jS)
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)r�get_machine_id�cfgr4�update�format�_get_activity_info�	isoformat�_support_old_machine_info�request_url�API_V1_ADD_CONTRACT_MACHINEr9r	�AttachInvalidTokenError�_raise_attach_forbidden_message�ContractAPIErrorr:�	json_dict)	�self�contract_token�
attachment_dt�
machine_idr4�
activity_infor3�backcompat_data�responser(r(r)�add_contract_machineJs,

�


�z%UAContractClient.add_contract_machine�returncCsT|��}|jt|d|d|d|dd�d�}|jdkr'tjt|j|jd��|jS)	z=Requests list of entitlements available to this machine type.�architecturer�kernel�virt�rQrrRrS)�query_paramsr6r7)r?rB�API_V1_AVAILABLE_RESOURCESr9r	rFr:rG)rHrLrNr(r(r)�available_resourcesps ��
	�z$UAContractClient.available_resourcesrIcCsN|��}|�dd�|�i�|jt|d�}|jdkr$tjt|j|jd��|j	S)Nr-r.�r4r6r7)
r4r=r>rB�API_V1_GET_CONTRACT_USING_TOKENr9r	rFr:rG)rHrIr4rNr(r(r)�get_contract_using_token�s�
�z)UAContractClient.get_contract_using_token�instancecCsv|jtj|jd�|jd�}|jdkr0|j�dd�}|r&t�	|�t
j|d��t
jt|j|j
d��|j�d|j�|jS)	z�Requests 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.
        )�
cloud_type)r3r6�message�)�	error_msgr7zcontract-token)rB�,API_V1_GET_CONTRACT_TOKEN_FOR_CLOUD_INSTANCEr>r\�identity_docr9rG�get�LOG�debugr	�InvalidProImagerFr:r<�write_cache)rHr[rN�msgr(r(r)�%get_contract_token_for_cloud_instance�s$
��

�z6UAContractClient.get_contract_token_for_cloud_instanceT�
machine_token�resourcerK�	save_filecCs�|st�|j�}|��}|�dd�|�i�tj||d�}|j||d�}|jdkr3t	j
t|j|jd��|j�d�rA|jd|j
d<|rN|j�d�|�|j
�|j
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.
        @save_file: If the machine access should be saved on the user machine

        @return: Dict of the JSON response containing entitlement accessInfo.
        r-r.)rj�machinerXr6r7�expireszmachine-access-{})rr;r<r4r=r>�"API_V1_GET_RESOURCE_MACHINE_ACCESSrBr9r	rFr:rbrGrf)rHrirjrKrkr4r8rNr(r(r)�get_resource_machine_access�s*�
��z,UAContractClient.get_resource_machine_accesscCs�|jjj}|jj�d�}t�|j�}|��}tj	||d�}|�
�}|�dd�	|�i�|j|||d�}|j
dkrBtj||j
|jd��|jrW|jj}|j|d<|jj�|�d	Sd	S)
z�Report current activity token and enabled services.

        This will report to the contracts backend all the current
        enabled services in the system.
        �machineToken��contractrlr-r.)r4r3r6r7r2N)r<�machine_token_file�contract_idrirbrr;r?�API_V1_UPDATE_ACTIVITY_TOKENr>r4r=rBr9r	rFr:rG�write)rHrtrirK�request_datar8r4rNr(r(r)�update_activity_token�s&
�

�
�z&UAContractClient.update_activity_token�magic_tokenc
Cs�|��}|�dd�|�i�z	|jt|d�}Wntjy-}z	t�|�t�	��d}~ww|j
dkr7t���|j
dkr@t���|j
dkrOtj
t|j
|jd��|jS)	z�Request 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
        r-r.rXNr5�r6r7)r4r=r>rB�"API_V1_GET_MAGIC_ATTACH_TOKEN_INFOr	�UrlErrorrc�	exception�ConnectivityErrorr9�MagicAttachTokenError�MagicAttachUnavailablerFr:rG�rHryr4rN�er(r(r)�get_magic_attach_token_info�s,
�
��


�z,UAContractClient.get_magic_attach_token_infoc
Cs�|��}z
|jt|dd�}Wntjy$}z	t�|�t���d}~ww|jdkr.t�	��|jdkr=tj
t|j|jd��|jS)z)Create a magic attach token for the user.�POST�r4�methodNrzr6r7)
r4rB�API_V1_NEW_MAGIC_ATTACHr	r|rcr}r~r9r�rFr:rG)rHr4rNr�r(r(r)�new_magic_attach_tokens*
�
��

�z'UAContractClient.new_magic_attach_tokenc
Cs�|��}|�dd�|�i�z
|jt|dd�}Wntjy.}z	t�|�t�	��d}~ww|j
dkr8t���|j
dkrAt���|j
dkrJt�
��|j
d	krYtjt|j
|jd
��dS)z)Revoke a magic attach token for the user.r-r.�DELETEr�Ni�r5rzr6r7)r4r=r>rB�API_V1_REVOKE_MAGIC_ATTACHr	r|rcr}r~r9� MagicAttachTokenAlreadyActivatedrr�rFr:r�r(r(r)�revoke_magic_attach_token3s4
�
��



��z*UAContractClient.revoke_magic_attach_tokenrtc	Cs�|st�|j�}|��}|�dd�|�i�tj||d�}|��}|j|d||d|d|d|dd	�d
�}|j	dkrFt
j||j	|jd��|j�
d
�rT|jd
|jd
<|jS)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.
        r-r.rq�GETrQrrRrSrT)r�r4rUr6r7rm)rr;r<r4r=r>�API_V1_GET_CONTRACT_MACHINEr?rBr9r	rFr:rbrG)rHrirtrKr4r8rLrNr(r(r)�get_contract_machineNs4���

�z%UAContractClient.get_contract_machinec	Cs�|st�|j�}|��}|�dd�|�i�||��d�}t|�}tj||d�}|j	||d|d�}|j
dkr@tj||j
|j
d��|j�d	�rN|jd	|jd	<|jS)
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
        r-r.r0rqr�)r4r�r3r6r7rm)rr;r<r4r=r>r?rA�API_V1_UPDATE_CONTRACT_MACHINErBr9r	rFr:rbrG)	rHrirtrKr4r3rMr8rNr(r(r)�update_contract_machineys*���

�z(UAContractClient.update_contract_machinecCs�t��jt��jt��jt��t��t��t	�
�d�}t|j�j
rQt|j�j}t��}|jjjp5t�|j�|jjjdd�|D�dd�|D�|rL|j��ndd�}ni}i|�|�S)z9Return a dict of activity info data for contract requests)�distributionrRrrQ�desktoprS�
clientVersioncSsg|]}|j�qSr()�name��.0�servicer(r(r)�
<listcomp>�sz7UAContractClient._get_activity_info.<locals>.<listcomp>cSsi|]
}|jr|j|j�qSr()�variant_enabledr��variant_namer�r(r(r)�
<dictcomp>�s��z7UAContractClient._get_activity_info.<locals>.<dictcomp>N)�
activityID�
activityToken�	resources�resourceVariantsr/)r�get_release_infor��get_kernel_info�
uname_releaser�
get_dpkg_arch�
is_desktop�
get_virt_typer�get_versionrr<�is_attachedr�enabled_servicesr�readrs�activity_idr;�activity_token�attached_atr@)rH�machine_infor��attachment_datarLr(r(r)r?�s8�


�����z#UAContractClient._get_activity_info�N)NT)r r!r"�cfg_url_base_attrr
�retry�socket�timeoutrOr�strrrWrZr�AutoAttachCloudInstancerhr�boolrorxr�r�r�r�r�r?r(r(r(r)r*Gsb�%�!�����

�(&����

�/����
�(r*�request_bodyc	CsJ|�di�}|�d�||�d�|�d�|�d�|�d�dt��jd�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.
    r2r1rQr�rRr�Linux)r�rRr�type�release)r1r2rQ�os)rbrr�r�)r�rLr(r(r)rA�s	��rATr<�past_entitlements�new_entitlements�allow_enablerrPcCsVddlm}d}d}g}||�D]y}	z||	}
Wn	ty!Yqwg}zt||�|	i�|
||d�\}}WnJtjy[}
zt�|
�d}|�	|	�t�
d|	|
�WYd}
~
qd}
~
wty}
zt�|
�d}|�	|	�t�d|	|
�WYd}
~
qd}
~
ww|r�|r�t�
|	�qt�|�|r�tjd	d
�|D�d��|r�tjdd
�|D�d��dS)
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)r<�orig_access�
new_accessr�rTz+Failed to process contract delta for %s: %rNz5Unexpected error processing contract delta for %s: %rcS�g|]}|tjf�qSr()r�UNEXPECTED_ERROR�r�r�r(r(r)r�)s
�z.process_entitlements_delta.<locals>.<listcomp>)�failed_servicescSr�r()r�!E_ATTACH_FAILURE_DEFAULT_SERVICESr�r(r(r)r�/s��)�uaclient.entitlementsr��KeyError�process_entitlement_deltarbr	�UbuntuProErrorrcr}�append�error�	Exception�event�service_processed�services_failed�AttachFailureUnknownError�AttachFailureDefaultServices)r<r�r�r�rr��delta_error�unexpected_errorr�r��new_entitlement�deltas�service_enabledr�r(r(r)�process_entitlements_delta�sr�
�

��

���
�
�����r�Fr�r�c

Cs�ddlm}|rt|�t�||�}d}|rn|�di��d�}|s*|�di��d�}|s3tj||d��|�di��di��d	d
�}	z	||||	d�}
Wntjy_}zt	�
d|�|�d
}~ww|
||d�}|j|||d�}||fS)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_selectorr^)r<r�rz3Skipping entitlement deltas for "%s". No such classN)r<�
assume_yes�r�)r�r��apply_contract_overridesr
�get_dict_deltasrbr	� InvalidContractDeltasServiceType�EntitlementNotFoundErrorrcrd�process_contract_deltas)
r<r�r�r�rr�r��retr�r�ent_cls�excr�r(r(r)r�6s>�
�����r�rNcCs�|j�d�}|rJ|d}|d}|dkr(|d�t�}tj|||d�d�d��|dkr@|d�t�}tj|||d�d�d	��|d
krJtj|d��t���)N�info�
contractId�reasonzno-longer-effective�timez%m-%d-%Y)rt�date�contract_expiry_dateznot-effective-yet)rtr��contract_effective_dateznever-effective)rt)	rGrb�strftimerr	�AttachForbiddenExpired�AttachForbiddenNotYet�AttachForbiddenNever�AttachExpiredToken)rNr�rtr�r�r(r(r)rErs*��rEcCs�|jj}|j}|d}|ddd}t|�}|j||d�}|j�|�tj��|�	di��	dt�|��}|�
d|�t|||jjdd	�d
S)a
Request contract refresh from ua-contracts service.

    :param cfg: Instance of UAConfig for this machine.

    :raise UbuntuProError: on failure to update contract or error processing
        contract deltas
    :raise UrlError: On failure during a connection
    rp�machineTokenInfo�contractInfo�id)rirtr1z
machine-idFr�N)rsr�rir*r�rvrr;�cache_clearrbrfr�)r<�orig_entitlements�
orig_tokenrirt�contract_client�resprKr(r(r)�refresh�s(	�

�
�r�cCst|�}|��}|�dg�S)zDQuery available resources from the contract server for this machine.r�)r*rWrb)r<�clientr�r(r(r)�get_available_resources�sr�tokencCst|�}|�|�S)z/Query contract information for a specific token)r*rZ)r<rrr(r(r)�get_contract_information�s
rc
Cs�|j}|jj}|�dd�}|�di��di��dd�}|sdSt|�}|�||�}|�di��di��dd�}|r;|n|jj}|jj|krGdS|j�|�}	t|	�	��D]\}
}t
�|�|
i�|�}|rfdSqSdS)	Nrpr^r�r�r�F�effectiveToT)rirsr�rbr*r��contract_expiry_datetime�get_entitlements_from_token�sorted�itemsr
r�)
r<r�r�rirtr�r��resp_expiry�
new_expiry�curr_entitlementsr�r�r�r(r(r)�is_contract_changed�s@
�
������r�override_selector�selector_valuescCs<d}|��D]\}}||f|��vrdS|t|7}q|S)Nr)r�OVERRIDE_SELECTOR_WEIGHTS)r
r�override_weight�selector�valuer(r(r)�_get_override_weight�srr��series_namer\rc
Cszi}||d�}|r
||d<|�di��|i�}|r||td<t�|�dg��}|D]}t|�d�|�}	|	r:|||	<q*|S)N)rrrrr�	overridesr)�popr�copy�deepcopyrbr)
r�rr\rrrr�general_overrides�override�weightr(r(r)�_select_overrides�s&
��
��rrcCs�ddlm}tt|t�d|vg�std�|���|dur!t��j	n|}|�\}}|�
di�}t||||�}t|�
��D]%\}	}
|
�
�D]\}}|d�
|�}
t|
t�rY|
�|�qC||d|<qCq;dS)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.identityr�all�
isinstance�dict�RuntimeErrorr>rr�rrbrrrr=)r�rrrrr\�_�orig_entitlementr�_weight�overrides_to_apply�keyr�currentr(r(r)r�
s*��
�
��r�cCs�t|�js
tjdfSt}t}|jj}|dur!t�	d�tj
|fSd|kr+|kr2nntj|fS||kr=dkrDnntj|fS||krNtj
|fStj
|fS)z/Return a tuple [ContractExpiryStatus, num_days]rNz:contract effectiveTo date is null - assuming it is expired)rr�rr#rrrs�contract_remaining_daysrc�warningr'r%r&r$)r<�grace_period�pending_expiry�remaining_daysr(r(r)�get_contract_expiry_status>s"

�




r.)T)FTr�)NN)Jr�enum�loggingr��typingrrrrr�uaclientrrr	r
rrr
r�-uaclient.api.u.pro.status.enabled_services.v1r�(uaclient.api.u.pro.status.is_attached.v1r�uaclient.configr�uaclient.defaultsrrr�uaclient.files.state_filesr�
uaclient.httprrCr�r�rVrnr`rurYr{r�r�r�get_event_loggerr��	getLogger�replace_top_level_logger_namer rc�unique�Enumr�UAServiceClientr*r!rAr�r�r�r��HTTPResponse�NamedMessagerEr�rrr�intrrr�r.r(r(r(r)�<module>s�(
����� ��
�
���
�W��
�
���

�<�
�"&
�
�
��
����
��
���
�1�
�