Your IP : 216.73.216.52


Current Path : /usr/lib/python3/dist-packages/uaclient/__pycache__/
Upload File :
Current File : //usr/lib/python3/dist-packages/uaclient/__pycache__/contract.cpython-38.pyc

U

8�-d�m�	@s�ddlZddlZddlmZmZmZmZmZddlm	Z	m
Z
mZmZm
Z
mZmZddlmZddlmZddlmZdZdZd	Zd
ZdZdZd
ZdZdddd�Ze
��Z Gdd�de
j!�Z"d4eee#efee#efe$e$dd�dd�Z%d5eee#efee#efe$e$eee$fd�dd�Z&ej'ej(d�dd�Z)d6ee#d �d!d"�Z*eeed#�d$d%�Z+ee#ee#efd&�d'd(�Z,ee$d#�d)d*�Z-ee#e#fee#e#fe.d+�d,d-�Z/ee#efe#e#ee.ee#effd.�d/d0�Z0d7ee#efee#dd1�d2d3�Z1dS)8�N)�Any�Dict�List�Optional�Tuple)�clouds�event_logger�
exceptions�messages�
serviceclient�system�util)�UAConfig)�ATTACH_FAIL_DATE_FORMAT)�UserFacingStatusz/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�cloudc@s�eZdZdZejZeje	j
dddgd�d/dd��Zee
efd�d	d
�Ze
ee
efd�dd
�Zeje	j
dddgd�ejd�dd��Zd0e
e
ee
ee
efd�dd�Zd1e
e
ee
ed�dd�Zdd�Ze
ee
efd�dd�Zee
efd�dd�Ze
d�dd �Zd2e
e
ee
ee
efd�d!d"�Zd3e
e
ee
ed�d#d$�Zee
efd%�d&d'�Zd(d)�Zd*d+�Zd4ee
d,�d-d.�Z dS)5�UAContractClientZcontract_urlrr)Zretry_sleepsNcCs~|��}|�dd�|�i�|�|�}|jt||d�\}}|jj�|�t	j
��|�di��d|�d��}|j�
d|�|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 {})�data�headers�machineTokenInfo�	machineId�
machine-id)r�update�format�_get_platform_data�request_url�API_V1_CONTEXT_MACHINE_TOKEN�cfg�machine_token_file�writer�get_machine_id�cache_clear�get�write_cache)�self�contract_token�
machine_idrr�
machine_token�_headers�r0�3/usr/lib/python3/dist-packages/uaclient/contract.py�request_contract_machine_attach*s 
�

�z0UAContractClient.request_contract_machine_attach)�returncCs|jt|��d�\}}|S)z=Requests list of entitlements available to this machine type.)�query_params)r"�API_V1_RESOURCES�_get_platform_basic_info)r+Zresource_responserr0r0r1�request_resourcesEs
�
z"UAContractClient.request_resources)r,r3cCs2|��}|�dd�|�i�|jt|d�\}}|S)Nrr�r)rrr r"�API_V1_CONTRACT_INFORMATION)r+r,rZ
response_dataZ_response_headersr0r0r1�request_contract_informationLs�
z-UAContractClient.request_contract_information)�instancec
Cs�z"|jtj|jd�|jd�\}}WnPtjk
rr}z0|j�dd�}|r^t	�
|�tj|d��|�W5d}~XYnX|j�
d|�|S)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)r�message�)Z	error_msgNzcontract-token)r"�API_V1_AUTO_ATTACH_CLOUD_TOKENr r<Zidentity_docr	�ContractAPIError�	api_errorr)�logging�debugZInvalidProImager$r*)r+r;�responser/�e�msgr0r0r1�"request_auto_attach_contract_tokenVs
��
z3UAContractClient.request_auto_attach_contract_token)r.�resourcer-r3cCsz|st�|j�}|��}|�dd�|�i�tj||d�}|j||d�\}}|�d�rb|d|d<|j�	d�|�|�|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)rH�machiner8�expireszmachine-access-{})
rr'r$rrr �#API_V1_TMPL_RESOURCE_MACHINE_ACCESSr"r)r*)r+r.rHr-r�urlZresource_accessr0r0r1�request_resource_machine_accessqs �
�z0UAContractClient.request_resource_machine_access)r.�contract_idr-r3cCs|j|||d�S)z6Update existing machine-token for an attached machine.)r.rNr-)�_request_machine_token_update)r+r.rNr-r0r0r1�request_machine_token_update�s
�z-UAContractClient.request_machine_token_updatec	Cs�|jjj}|jj�d�}t�|j�}|�|�}tj	||d�}|�
�}|�dd�	|�i�|j|||d�\}}|r�|jj}||d<|jj�
|�dS)z�Report current activity token and enabled services.

        This will report to the contracts backend all the current
        enabled services in the system.
        �machineToken�ZcontractrIrr)rr�activityInfoN)r$r%rNr.r)rr'�_get_activity_info�API_V1_MACHINE_ACTIVITYr rrr"r&)	r+rNr.r-Zrequest_datarLrrD�_r0r0r1�report_machine_activity�s

�z(UAContractClient.report_machine_activity)�magic_tokenr3c
Cs�|��}|�dd�|�i�z|jt|d�\}}Wn�tjk
r�}z8t|d�rv|jdkrdt�	��n|jdkrvt�
��|�W5d}~XYn:tjk
r�}zt�
t|��t���W5d}~XYnX|S)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
        rrr8�code��N)rrr r"�API_V1_MAGIC_ATTACHr	r@�hasattrrY�MagicAttachTokenError�MagicAttachUnavailable�UrlErrorrB�	exception�str�ConnectivityError)r+rXrrDrVrEr0r0r1�get_magic_attach_token_info�s$�



z,UAContractClient.get_magic_attach_token_infoc
Cs�|��}z|jt|dd�\}}Wnrtjk
rZ}z|jdkrFt���|�W5d}~XYn:tjk
r�}zt�	t
|��t���W5d}~XYnX|S)z)Create a magic attach token for the user.�POST�r�methodr[N)rr"r\r	r@rYr_r`rBrarbrc)r+rrDrVrEr0r0r1�new_magic_attach_token�s�
z'UAContractClient.new_magic_attach_token)rXc
Cs�|��}|�dd�|�i�z|jt|dd�Wn�tjk
r�}zLt|d�r�|jdkrbt�	��n&|jdkrvt�
��n|jdkr�t���|�W5d	}~XYn:tjk
r�}zt
�t|��t���W5d	}~XYnXd	S)
z)Revoke a magic attach token for the user.rrZDELETErfrYi�rZr[N)rrr r"r\r	r@r]rYZ MagicAttachTokenAlreadyActivatedr^r_r`rBrarbrc)r+rXrrEr0r0r1�revoke_magic_attach_token�s(�






z*UAContractClient.revoke_magic_attach_tokencCsv|s|�|��dd�}|��}|�dd�|�i�tj||d�}|j|d||��dd�\}}|�d	�rr|d	|d	<|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.
        rNrrrRZGETr)rgrr4�timeoutrJ)r!r)rrr �*API_V1_TMPL_CONTEXT_MACHINE_TOKEN_RESOURCEr"r6)r+r.rNr-rrLrDr0r0r1�get_updated_contract_infos*
���

z*UAContractClient.get_updated_contract_infocCs�|��}|�dd�|�i�|�|�}|��|d<tj||dd�}|j||d|d�\}}|�d�rp|d|d<|�d	i��d|�d��}|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
        rrrSrrRre)rrgrrJr)rrr r!rTrkr"r))r+r.rNr-rrrLrDr0r0r1rO)s*
��

�z.UAContractClient._request_machine_token_update)rDcCsN|jj�|�tj��|�d�}|�di��d|�d��}|j�d|�dS)Nrrr)	r$r%r&rr'r(r!r)r*)r+rDrr-r0r0r1�'update_files_after_machine_token_updateJs

�z8UAContractClient.update_files_after_machine_token_updatecCs6|st�|j�}t��}|��}|�d�}|||d�S)z<Return a dict of platform-related data for contract requests�arch)r�architecture�os)rr'r$�get_platform_info�copy�pop)r+r-�platformZplatform_osrnr0r0r1r!Us
�z#UAContractClient._get_platform_datacCs&t��}|d|d|d|dd�S)z?Return a dict of platform basic info for some contract requestsrnr�kernel�virt)rorrurv)rrq)r+rtr0r0r1r6bs�z)UAContractClient._get_platform_basic_info)r-csNddlm}|st��j�}�jjjp(|}�fdd�|D�}|�jjj|d�S)z9Return a dict of activity info data for contract requestsr)�ENTITLEMENT_CLASSEScs0g|](}|�j���dtjkr|�j�j�qS)r)r$Zuser_facing_statusrZACTIVE�name)�.0Zent�r+r0r1�
<listcomp>ws�z7UAContractClient._get_activity_info.<locals>.<listcomp>)Z
activityIDZ
activityToken�	resources)�uaclient.entitlementsrwrr'r$r%�activity_idZactivity_token)r+r-rwr~Zenabled_servicesr0rzr1rTls
��z#UAContractClient._get_activity_info)N)N)N)N)N)N)!�__name__�
__module__�__qualname__Zcfg_url_base_attrr	r@Z
api_error_clsr
Zretry�socketrjr2rrbrr7r:rZAutoAttachCloudInstancerGrrMrPrWrdrhrirlrOrmr!r6rTr0r0r0r1r%s`
�
��
�#��
#�
�'��"
�

rT)r$�past_entitlements�new_entitlements�allow_enablerr3c
CsPddlm}d}d}||�D]�}z||}	Wntk
rDYqYnXz"t||�|i�|	||d�\}
}Wn�tjk
r�d}t�|�t	�
��t�dj
||	d��W5QRXYqtk
r�d}t�|�t	�
��t�dj
||	d��W5QRXYqX|r|
rt�|�q|�r0tjtjjtjjd	��n|�rLtjtjjtjjd	��d
S)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�rTz4Failed to process contract delta for {name}: {delta})rxZdeltaz>Unexpected error processing contract delta for {name}: {delta}�rF�msg_codeN)r}r��KeyError�process_entitlement_deltar)r	�UserFacingError�eventZservice_failedr
�disable_log_to_consolerB�errorr �	ExceptionraZservice_processedr
ZUNEXPECTED_ERRORrFrxZATTACH_FAILURE_DEFAULT_SERVICES)r$r�r�r�rr�Zdelta_errorZunexpected_errorrx�new_entitlement�deltasZservice_enabledr0r0r1�process_entitlements_delta�s`

�

��

����r�F)r$r�r�r�rr3c

Cs�ddlm}|rt|�t�||�}d}|r�|�di��d�}|sT|�di��d�}|sztjj||d�}	t	j
|	j|	jd��z|||d�}
Wn4t	j
k
r�}zt�d	|�|�W5d
}~XYnX|
||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 UserFacingError: 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�entitlement�type)Zorig�newr�)r$rxz3Skipping entitlement deltas for "%s". No such classN)r$Z
assume_yes)r�)r}r��apply_contract_overridesr
�get_dict_deltasr)r
Z$INVALID_CONTRACT_DELTAS_SERVICE_TYPEr r	r�rFrxZEntitlementNotFoundErrorrBrCZprocess_contract_deltas)
r$r�r�r�rr�r�ZretrxrFZent_cls�excr�r0r0r1r��s<���r�)rEr3cCs�tj}t|d�r�d|jkr�|jd}|d}|d}d}|dkrz|d�t�}|d�d�|d�}tjj||d	�}||_nX|d
kr�|d�t�}|d�d�|d�}tj	j||d	�}||_n|dkr�tj
j|d
�}|r�tjj|jd�}|j
|_
|j|_|S)NrA�infoZ
contractId�reasonzno-longer-effective�timez%m-%d-%Y)Zcontract_expiry_daterN)rN�dateznot-effective-yet)Zcontract_effective_daterNznever-effective)rN)r�)r
ZATTACH_EXPIRED_TOKENr]rA�strftimerZATTACH_FORBIDDEN_EXPIREDr �additional_infoZATTACH_FORBIDDEN_NOT_YETZATTACH_FORBIDDEN_NEVERZATTACH_FORBIDDENrFrx)rErFr�rNr�Z
reason_msgr�r�r0r0r1� _create_attach_forbidden_messagesF
�����r��r,cCs8|j}|jj}|r.|r.tj}tj|j|jd��t	|�}|r�z|j
|d�Wn�tjk
r�}z�t|tj
�r�t|d�r�|jdkr�t���n(|jdkr�t|�}tj|j|j|jd��|�t���t�t|��W5QRXt���W5d}~XYnXn0|d}|d	d
d}	|j||	d�}
|�|
�t|||jj|�dS)
afRequest contract refresh from ua-contracts service.

    Compare original token to new token and react to entitlement deltas.

    :param cfg: Instance of UAConfig for this machine.
    :param contract_token: String contraining an optional contract token.
    :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.

    :raise UserFacingError: on failure to update contract or error processing
        contract deltas
    :raise UrlError: On failure to contact the server
    r�r�rYrZi�)rFr�r�NrQr�contractInfo�id)r.rN)r.r%�entitlementsr
Z-UNEXPECTED_CONTRACT_TOKEN_ON_ATTACHED_MACHINEr	r�rFrxrr2r`�
isinstancer@r]rYZAttachInvalidTokenErrorr�r�r
r�rBrarbrcrPrmr�)r$r,r��
orig_token�orig_entitlementsrF�contract_clientrEr.rN�respr0r0r1�request_updated_contract1sP�




�
�
�r�)r$r3cCst|�}|��}|�dg�S)zDQuery available resources from the contract server for this machine.r|)rr7r))r$�clientr|r0r0r1�get_available_resourcesmsr�)r$�tokenr3cCst|�}|�|�S)z/Query contract information for a specific token)rr:)r$r�r�r0r0r1�get_contract_informationtsr�c
Cs�|j}|jj}|�dd�}|�di��di��dd�}|s>dSt|�}|�||�}|�di��di��dd�}|rv|n|jj}|jj|kr�dS|j�|�}	t|	�	��D]&\}
}t
�|�|
i�|�}|r�dSq�dS)	NrQr>rr�r�FZeffectiveToT)r.r%r�r)rrlZcontract_expiry_datetimeZget_entitlements_from_token�sorted�itemsr
r�)
r$r�r�r.rNr�r�Zresp_expiryZ
new_expiryZcurr_entitlementsrxr�r�r0r0r1�is_contract_changedzsV����������
�r�)�override_selector�selector_valuesr3cCs<d}|��D]*\}}||f|��kr*dS|t|7}q|S)Nr)r��OVERRIDE_SELECTOR_WEIGHTS)r�r�Zoverride_weight�selector�valuer0r0r1�_get_override_weight�sr�)r��series_namer<r3c	Cshi}||d�}|�di��|i�}|r2||td<|�dg�}|D] }t|�d�|�}|rB|||<qB|S)N)rrrr�	overridesr�)rsr�r�)	r�r�r<r�r�rZgeneral_overrides�overrideZweightr0r0r1�_select_overrides�s"
���
r�)r�rr3c
Cs�ddlm}tt|t�d|kg�s0td�|���|dkrDt��dn|}|�\}}|�	di�}t
|||�}t|���D]J\}}	|	��D]8\}
}|d�	|
�}t|t�r�|�
|�q�||d|
<q�qvdS)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: {}Nr)Zuaclient.clouds.identityr��allr��dict�RuntimeErrorr rrqr)r�r�r�r)
r�rr�r�r<rVZorig_entitlementr�Z_weightZoverrides_to_apply�keyr�Zcurrentr0r0r1r��s$���

r�)T)FT)NF)N)2rBr��typingrrrrrZuaclientrrr	r
rrr
Zuaclient.configrZuaclient.defaultsrZ(uaclient.entitlements.entitlement_statusrr#rkr5rKr?rUr9r\r�Zget_event_loggerr�ZUAServiceClientrrb�boolr�r�r@ZNamedMessager�r�r�r�r��intr�r�r�r0r0r0r1�<module>s�$	��f�

�O�


�8�,��<)

�
��
�