o
    ÙKÕiøº  ã                   @   s"  d dl Z 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
mZmZmZ d dlmZmZ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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*m+Z+ e ,¡ Z-e .e /e0¡¡Z1G d
d„ dƒZ2G dd„ de j3d�Z4dS )é    N)Údatetime)ÚAnyÚDictÚListÚOptionalÚSetÚTupleÚTypeÚUnion)ÚapiÚaptÚconfigÚcontractÚevent_loggerÚ
exceptionsÚhttpÚmessagesÚsnapÚsystemÚutil)Ú_is_attached)ÚApplicabilityStatusÚApplicationStatusÚCanDisableFailureÚCanDisableFailureReasonÚCanEnableFailureÚCanEnableFailureReasonÚContractStatusÚUserFacingStatus)Úmachine_token)Ústatus_cache_file)ÚMessagingOperationsDictÚStaticAffordancec                   @   s$   e Zd Zded dejfdd„ZdS )ÚEntitlementWithMessageÚentitlementÚUAEntitlementÚ	named_msgc                 C   s   || _ || _d S ©N)r$   r&   )Úselfr$   r&   © r)   ú</usr/lib/python3/dist-packages/uaclient/entitlements/base.pyÚ__init__)   s   
zEntitlementWithMessage.__init__N)Ú__name__Ú
__module__Ú__qualname__r	   r   ÚNamedMessager+   r)   r)   r)   r*   r#   (   s    þýr#   c                   @   sš  e Zd ZdZdZdZdZdZdZdZ	dZ
dZdZdZdZdZedefdd„ƒZedee fd	d
„ƒZeejdefdd„ƒƒZeejdefdd„ƒƒZedefdd„ƒZdeeef deeeej  f fdd„Z!edefdd„ƒZ"edee#df fdd„ƒZ$edee%df fdd„ƒZ&edee%df fdd„ƒZ'edee(d  df fdd„ƒZ)deee(d  f fdd „Z*de+e fd!d"„Z,deee(d  f fd#d$„Z-edeee(d  f fd%d&„ƒZ.edeee(d  f fd'd(„ƒZ/eded  fd)d*„ƒZ0defd+d,„Z1ed-d.„ ƒZ2ede3fd/d0„ƒZ4					dŽd1ee5j6 d2ed3ed4ed5eee  ddfd6d7„Z7d8d9„ Z8ed:d;„ ƒZ9ejde:fd<d=„ƒZ;ejde:fd>d?„ƒZ<de:fd@dA„Z=de:fdBdC„Z>deeee? f fdDdE„Z@dFeAjBdeeeCde?f f fdGdH„ZDdFeAjBdefdIdJ„ZEdefdKdL„ZFdFeAjBdefdMdN„ZGdefdOdP„ZHejdFeAjBdefdQdR„ƒZIdee% fdSdT„ZJdefdUdV„ZKdFeAjBdeeeej  f fdWdX„ZLdYdZ„ ZMd[d\„ ZNdFeAjBdeeeej  f fd]d^„ZO	d�d_edeeeeP f fd`da„ZQdFeAjBdeeeeP f fdbdc„ZRejdFeAjBdefddde„ƒZSdefdfdg„ZTdee(d   fdhdi„ZUdFeAjBdeeeej  f fdjdk„ZVdefdldm„ZW	d�dnedoeddfdpdq„ZXdeeYeej  f fdrds„ZZde[fdtdu„Z\dee]eej  f fdvdw„Z^ejdee_eej  f fdxdy„ƒZ`deeeej  f fdzd{„Zadee fd|d}„Zbdefd~d„Zcde_fd€d�„Zdd‚eeef dƒee defd„d…„Ze		d�d†eeef d‡eeef dˆed‰edef
dŠd‹„ZfdFeAjBfdŒd�„ZgdS )‘r%   NFÚ r)   TÚreturnc                 C   ó   dS )z?The lowercase name of this entitlement, in case it is a variantr0   r)   ©r(   r)   r)   r*   Úvariant_nameS   ó   zUAEntitlement.variant_namec                 C   s$   | j g}| j| j kr| | j¡ |S )z1The list of names this entitlement may be called.)ÚnameÚpresentation_nameÚappend)r(   Úvalid_namesr)   r)   r*   r9   X   s   zUAEntitlement.valid_namesc                 C   r2   )z,The human readable title of this entitlementNr)   r3   r)   r)   r*   Útitle`   ó   zUAEntitlement.titlec                 C   r2   )z&A sentence describing this entitlementNr)   r3   r)   r)   r*   Údescriptionf   r;   zUAEntitlement.descriptionc                 C   s:   | j r| jS | jjr| j di ¡ di ¡ d| j¡S | jS )z/The user-facing name shown for this entitlementr$   ÚaffordancesÚpresentedAs)Ú
is_variantr4   Úmachine_token_fileÚ
is_presentÚentitlement_cfgÚgetr6   r3   r)   r)   r*   r7   l   s   
ýzUAEntitlement.presentation_nameÚplatform_checkc                 C   r2   )zÃVerify specific platform checks for a service.

        This should only be used if the service requires custom platform checks
        to check if it is available or not in the machine.
        ©TNr)   )r(   rD   r)   r)   r*   Úverify_platform_checksz   s   z$UAEntitlement.verify_platform_checksc                 C   sF   | j }| jr!dd„ | j ¡ D ƒ}d dtj d g| ¡}||7 }|S )z$Help information for the entitlementc                 S   s   g | ]\}}d   ||j¡‘qS )z
  * {}: {})Úformatr<   )Ú.0r4   Úvariant_clsr)   r)   r*   Ú
<listcomp>Š   s    ÿÿz+UAEntitlement.help_info.<locals>.<listcomp>Ú
z

)Ú	help_textÚvariantsÚitemsÚjoinr   ÚCLI_HELP_VARIANTS_HEADER)r(   rL   Úvariant_itemsÚvariant_textr)   r)   r*   Ú	help_info„   s   þÿÿzUAEntitlement.help_info.c                 C   r2   )Nr)   r)   r3   r)   r)   r*   Ústatic_affordancesš   ó   z UAEntitlement.static_affordancesc                 C   ó   | j S )a  
        Return a list of packages that aren't compatible with the entitlement.
        When we are enabling the entitlement we can directly ask the user
        if those entitlements can be disabled before proceding.
        Overridden in livepatch and fips
        )Ú_incompatible_servicesr3   r)   r)   r*   Úincompatible_servicesž   ó   z#UAEntitlement.incompatible_servicesc                 C   rV   )a  
        Return a list of packages that must be active before enabling this
        service. When we are enabling the entitlement we can directly ask
        the user if those entitlements can be enabled before proceding.
        Overridden in ros and ros-updates.
        )Ú_required_servicesr3   r)   r)   r*   Úrequired_services¨   rY   zUAEntitlement.required_servicesc                 C   rV   )a  
        Return a list of packages that depend on this service.
        We will use that list during disable operations, where
        a disable operation will also disable all of the services
        required by the original service
        Overriden in esm-apps and esm-infra
        )Ú_dependent_servicesr3   r)   r)   r*   Údependent_services²   s   	z UAEntitlement.dependent_servicesc                 C   ó   i S r'   r)   r3   r)   r)   r*   Ú_get_variants½   s   zUAEntitlement._get_variantsc                 C   sP   t ƒ }|  ¡ }| di ¡ dg ¡}|D ]}| di ¡ d¡}|r%| |¡ q|S )zV
        Fetch all available variants defined in the Contract Server response
        r$   Ú	overridesÚselectorÚvariant)ÚsetÚ_base_entitlement_cfgrC   Úadd)r(   Úvalid_variantsrB   r`   Úoverriderb   r)   r)   r*   Ú_get_contract_variantsÀ   s   
€z$UAEntitlement._get_contract_variantsc                 C   s`   |   ¡ }|  ¡ }d|v rd|d i}ni }t|ƒD ]}||v r%|| ||< qt|ƒdkr.|S i S )NÚgenericé   )r_   rh   ÚsortedÚlen)r(   Úservice_variantsÚcontract_variantsrf   rb   r)   r)   r*   Ú_get_valid_variantsÏ   s   €z!UAEntitlement._get_valid_variantsc                 C   s   | j ri S |  ¡ S )zf
        Return a list of services that are considered a variant
        of the main service.
        )r?   ro   r3   r)   r)   r*   rM   Þ   s   zUAEntitlement.variantsc                    s$   ˆ j si S ‡ fdd„ˆ  ¡  ¡ D ƒS )zw
        On a variant, return the other variants of the main service.
        On a non-variant, returns empty.
        c                    s    i | ]\}}|ˆ j kr||“qS r)   )r4   )rH   r6   Úclsr3   r)   r*   Ú
<dictcomp>ð   s
    
þz0UAEntitlement.other_variants.<locals>.<dictcomp>)r?   ro   rN   r3   r)   r3   r*   Úother_variantsè   s
   

þzUAEntitlement.other_variantsc                 C   sR   | j  ¡ D ]!}|jdkrq|| j| j| jd�}| ¡ \}}|tjkr&|  S qdS )z¢
        On an enabled service class, return the variant that is enabled.
        Return None if no variants exist or none are enabled (e.g. access-only)
        ri   )ÚcfgÚcalled_nameÚaccess_onlyN)	rM   Úvaluesr4   rs   Ú_called_nameru   Úapplication_statusr   ÚENABLED)r(   rI   rb   ÚstatusÚ_r)   r)   r*   Úenabled_variantö   s   
ý
ÿzUAEntitlement.enabled_variantc                 C   r2   )zt
        Only implemented on variant classes.
        Returns True if this variant should be auto-selected.
        Fr)   r3   r)   r)   r*   Úvariant_auto_select	  s   z!UAEntitlement.variant_auto_selectc                 C   s   t | j ¡ ƒ}|r|d S dS )zº
        Cannot actually set the return type because
        https://github.com/python/typing/issues/266
        affects xenial.

        :rtype: Optional[Type["UAEntitlement"]]
        r   N)ÚlistrM   rv   )r(   rM   r)   r)   r*   Údefault_variant  s   	zUAEntitlement.default_variantc                 C   r^   r'   r)   r3   r)   r)   r*   Ú	messaging   rU   zUAEntitlement.messagingrs   rt   ru   ÚpurgeÚ
extra_argsc                 C   sT   |st  ¡ }|| _t ¡ | _|| _|| _|dur|| _ng | _|| _	d| _
d| _dS )z]Setup UAEntitlement instance

        @param config: Parsed configuration dictionary
        NF)r   ÚUAConfigrs   r   Úget_machine_token_filer@   ru   r�   r‚   rw   Ú_valid_serviceÚ_is_sources_list_updated)r(   rs   rt   ru   r�   r‚   r)   r)   r*   r+   $  s   

zUAEntitlement.__init__c                 C   s   t  | j ¡  | ji ¡¡S r'   )ÚcopyÚdeepcopyr@   ÚentitlementsrC   r6   r3   r)   r)   r*   rd   >  s   ÿz#UAEntitlement._base_entitlement_cfgc                 C   s*   |   ¡ }| jr	|s|S tj|| jd� |S )N)Úorig_accessrb   )rd   r?   r   Úapply_contract_overridesr4   ©r(   rB   r)   r)   r*   rB   C  s   
ÿzUAEntitlement.entitlement_cfgc                 C   r2   )z¡
        The number of steps that are reported as progress while enabling
        this specific entitlement that are not shared with other entitlements.
        Nr)   r3   r)   r)   r*   Úenable_stepsP  ó   zUAEntitlement.enable_stepsc                 C   r2   )z¢
        The number of steps that are reported as progress while disabling
        this specific entitlement that are not shared with other entitlements.
        Nr)   r3   r)   r)   r*   Údisable_stepsX  rŽ   zUAEntitlement.disable_stepsc                 C   sÀ   |   ¡ }| j di ¡ di ¡ d¡}|d ur t|ƒdkr |d7 }| j di ¡ di ¡ d¡}|d ur<t|ƒdkr<|d7 }|  ¡ D ]}|| | j¡ ¡ 7 }q@|  ¡ D ]}|| | j¡  ¡ 7 }qQ|S )Nr$   Ú
directivesÚrequiredSnapsr   rj   ÚrequiredPackages)	r�   rB   rC   rl   Úblocking_incompatible_servicesr$   rs   r�   Úblocking_required_services)r(   Útotal_stepsÚrequired_snapsÚrequired_packagesÚincompatible_serviceÚrequired_servicer)   r)   r*   Úcalculate_total_enable_steps`  s4   ýýÿþÿþz*UAEntitlement.calculate_total_enable_stepsc                 C   s,   |   ¡ }|  ¡ D ]}||| jƒ  ¡ 7 }q|S r'   )r�   Úblocking_dependent_servicesrs   )r(   r•   Údependent_servicer)   r)   r*   Úcalculate_total_disable_stepsz  s   z+UAEntitlement.calculate_total_disable_stepsc                 C   s  |   ¡ rt d| j¡ t | j¡ |  ¡ tj	ks'dt
tjtjj| jd�d�fS |  ¡ \}}|tjkrAdt
tjtjj| jd�d�fS |  ¡ \}}|tjkrUdt
tj|d�fS | jrc|  ¡ rcdt
tjƒfS | jrq|  ¡ sqdt
tjƒfS | js…| jr…dt
tj tj!j| jd�ƒfS dS )zÀ
        Report whether or not enabling is possible for the entitlement.

        :return:
            (True, None) if can enable
            (False, CanEnableFailure) if can't enable
        z(Updating contract on service '%s' expiryF©r:   ©ÚmessagerE   )"Úis_access_expiredÚLOGÚdebugr6   r   Úrefreshrs   Úcontract_statusr   ÚENTITLEDr   r   ÚNOT_ENTITLEDr   Ú
UNENTITLEDrG   r:   rx   r   ÚDISABLEDÚALREADY_ENABLEDÚapplicability_statusr   ÚINAPPLICABLErX   Údetect_incompatible_servicesÚINCOMPATIBLE_SERVICEr[   Úcheck_required_services_activeÚINACTIVE_REQUIRED_SERVICESÚsupports_access_onlyru   ÚACCESS_ONLY_NOT_SUPPORTEDÚ ENABLE_ACCESS_ONLY_NOT_SUPPORTED)r(   rx   r{   r«   Údetailsr)   r)   r*   Ú
can_enable€  sb   	þþ
þþ
ÿþÿþÿþÿþþ
zUAEntitlement.can_enableÚprogressc                 C   sà   |  d| j d¡¡ |  ¡ \}}|sJ|du rdS |jtjkr/|  |¡\}}|s.||_d|fS n|jtj	krF|  
|¡\}}|sE||_d|fS nd|fS |  d| j d¡¡ | jse|  |¡s^dS |  |¡sedS |  |¡}|sndS dS )aN  Enable specific entitlement.

        @return: tuple of (success, optional reason)
            (True, None) on success.
            (False, reason) otherwise. reason is only non-None if it is a
                populated CanEnableFailure reason. This may expand to
                include other types of reasons in the future.
        Úmessage_operationÚpre_can_enableN©FNFÚ
pre_enablerE   )Úemitr€   rC   rµ   Úreasonr   r®   Úhandle_incompatible_servicesr    r°   Ú_enable_required_servicesru   Úhandle_required_snapsÚhandle_required_packagesÚ_perform_enable)r(   r¶   rµ   ÚfailÚincompat_retÚerrorÚreq_retÚretr)   r)   r*   ÚenableÊ  sD   ÿÿþÿþ


zUAEntitlement.enablec           
   
   C   sò  | j  di ¡ di ¡ d¡}|du rdS t ¡ s'| dtjjdd�¡ t ¡  t 	¡ sc| dtjjd	d�¡ zt 
d¡ W n% tjyb } ztjd
|d� | dtjjdd�¡ W Y d}~nd}~ww t |¡ zt d¡ W n$ tjy“ } ztjd|d� t tjjdd�¡ W Y d}~nd}~ww t d| jjtj¡}t d| jjtj¡}tj||tjd� |r¹| tj¡ t|dd„ d�D ]5}|d }zt  |¡ W qÁ tj!yö   | dd¡}| d¡}	| dtj"j|d�¡ tj
||	|d� Y qÁw dS )z. "install snaps necessary to enable a service.r$   r�   r‘   NTÚinfoÚsnapd©Úpackagesz
snapd snapz!Failed to install snapd as a snap)Úexc_infozsnap install snapd)ÚcommandzFailed to refresh snapd snapzsnap refresh snapdr   Úhttps)Ú
http_proxyÚhttps_proxyÚretry_sleepsc                 S   s
   |   d¡S )Nr6   ©rC   )Úxr)   r)   r*   Ú<lambda>E  s   
 z5UAEntitlement.handle_required_snaps.<locals>.<lambda>)Úkeyr6   ÚclassicConfinementSupportFÚchannel)r   )r×   Úclassic_confinement_support)#rB   rC   r   Úis_snapd_installedr»   r   ÚINSTALLING_PACKAGESrG   Úinstall_snapdÚis_snapd_installed_as_a_snapÚinstall_snapr   ÚProcessExecutionErrorr¢   ÚwarningÚEXECUTING_COMMAND_FAILEDÚrun_snapd_wait_cmdÚrefresh_snapÚeventrÈ   r   Úvalidate_proxyrs   rÏ   ÚPROXY_VALIDATION_SNAP_HTTP_URLrÐ   ÚPROXY_VALIDATION_SNAP_HTTPS_URLÚconfigure_snap_proxyÚSNAP_INSTALL_RETRIESr¶   ÚINSTALLING_REQUIRED_SNAPSrk   Úget_snap_infoÚSnapNotInstalledErrorÚ INSTALLING_REQUIRED_SNAP_PACKAGE)
r(   r¶   r–   ÚerÏ   rÐ   Úsnap_pkgÚ	snap_namerØ   r×   r)   r)   r*   r¿     s–   ýÿþÿþ€þ
	ÿÿ€þÿÿýÿ
ÿþ
ýôz#UAEntitlement.handle_required_snapsc                    sP   | j  di ¡ di ¡ d¡}|sdS dd„ |D ƒ}t ¡ ‰ t‡ fdd„|D ƒƒS )ú/install packages necessary to enable a service.r$   r�   r’   Tc                 S   ó   g | ]}|d  ‘qS ©r6   r)   ©rH   Úpackager)   r)   r*   rJ   k  ó    zAUAEntitlement.are_required_packages_installed.<locals>.<listcomp>c                    s   g | ]}|ˆ v ‘qS r)   r)   )rH   Úrequired©Úinstalled_packagesr)   r*   rJ   o  rõ   )rB   rC   r   Úget_installed_packages_namesÚall)r(   r—   Úpackage_namesr)   r÷   r*   Úare_required_packages_installed^  s   ýÿz-UAEntitlement.are_required_packages_installedc                 C   sp   | j  di ¡ di ¡ d¡}|sdS |  |¡ dd„ |D ƒ}t d|¡ | tjjd 	|¡d	�¡ t
 |¡ dS )
rð   r$   r�   r’   Tc                 S   rñ   rò   r)   ró   r)   r)   r*   rJ   �  rõ   z:UAEntitlement.handle_required_packages.<locals>.<listcomp>zInstalling packages %rú rÊ   )rB   rC   Ú_update_sources_listr¢   r£   r¶   r   rÚ   rG   rO   r   Úrun_apt_install_command)r(   r¶   r—   rû   r)   r)   r*   rÀ   r  s    ý
ÿÿ
z&UAEntitlement.handle_required_packagesc                 C   s†   | j  di ¡ di ¡ d¡}|sdS dd„ |D ƒ}t|ƒdkr!dS t d|¡ d	 |¡}t tj	j
|d
�¡ t |tjj
|d
�¡ dS )rð   r$   r�   r’   Tc                 S   s    g | ]}|  d d¡r|d ‘qS )ÚremoveOnDisableFr6   rÒ   ró   r)   r)   r*   rJ   ™  s    
ýÿzCUAEntitlement.handle_removing_required_packages.<locals>.<listcomp>r   zUninstalling packages %rrý   rÊ   )rB   rC   rl   r¢   r£   rO   rã   rÈ   r   ÚUNINSTALLING_PACKAGESrG   r   Úremove_packagesÚUNINSTALLING_PACKAGES_FAILED)r(   r—   rû   Úpackage_names_strr)   r)   r*   Ú!handle_removing_required_packagesŒ  s.   ýþ
ÿÿþz/UAEntitlement.handle_removing_required_packagesc                 C   r2   )a  
        Enable specific entitlement. This should be implemented by subclasses.
        This method does the actual enablement, and does not check can_enable
        or handle pre_enable or post_enable messaging.

        @return: True on success, False otherwise.
        Nr)   ©r(   r¶   r)   r)   r*   rÁ   ±  s   	zUAEntitlement._perform_enablec                 C   sD   g }| j D ]}|j| jd� ¡ \}}|tjtjfv r| |¡ q|S )zI
        :return: List of incompatible services that are enabled
        ©rs   )rX   r$   rs   rx   r   ry   ÚWARNINGr8   ©r(   rÆ   ÚserviceÚ
ent_statusr{   r)   r)   r*   r“   ¼  s   
ÿþþ
€z,UAEntitlement.blocking_incompatible_servicesc                 C   ó   t |  ¡ ƒdkS )zÀ
        Check for incompatible services.

        :return:
            True if there are incompatible services enabled
            False if there are no incompatible services enabled
        r   )rl   r“   r3   r)   r)   r*   r­   Í  ó   z*UAEntitlement.detect_incompatible_servicesc                 C   sš   t j| jjdd�}|  ¡ D ]=}| | j¡}tjj| j|jd�}|r'd|f  S | 	dtj
j|jd�¡ | |¡\}}|sJ||rE|jf  S df  S qdS )	a)  
        Prompt user when incompatible services are found during enable.

        When enabling a service, we may find that there is an incompatible
        service already enable. In that situation, we can ask the user
        if the incompatible service should be disabled before proceeding.
        There are also different ways to configure that behavior:

        We can disable removing incompatible service during enable by
        adding the following lines into uaclient.conf:

        features:
          block_disable_on_enable: true
        z features.block_disable_on_enable)r   Úpath_to_value)Úservice_being_enabledr˜   FrÈ   ©r
  NrE   )r   Úis_config_value_truers   r“   r$   r   Ú#E_INCOMPATIBLE_SERVICE_STOPS_ENABLErG   r:   r»   ÚDISABLING_INCOMPATIBLE_SERVICEÚdisabler    )r(   r¶   Úcfg_block_disable_on_enabler
  ÚentÚe_msgrÆ   rÂ   r)   r)   r*   r½   ×  s.   þþÿþÿz*UAEntitlement.handle_incompatible_servicesc                 C   s   t |  ¡ ƒdkS )zÉ
        Check if all required services are active

        :return:
            True if all required services are active
            False is at least one of the required services is disabled
        r   )rl   r”   r3   r)   r)   r*   r¯     r  z,UAEntitlement.check_required_services_activec                 C   sB   g }| j D ]}| | j¡ ¡ \}}|tjtjfvr| |¡ q|S )zF
        :return: List of required services that are disabled
        )r[   r$   rs   rx   r   ry   r  r8   r	  r)   r)   r*   r”     s   
þ
€z(UAEntitlement.blocking_required_servicesc                 C   sŠ   |   ¡ D ]>}|j| jd�}| dtjj|jd�¡ | |¡\}}|sBd}|r3|j	r3|j	j
r3d|j	j
 }tjj||jd�}||f  S qdS )a,  
        Prompt user when required services are found during enable.

        When enabling a service, we may find that there are required services
        that must be enabled first. In that situation, we can ask the user
        if the required service should be enabled before proceeding.
        r  rÈ   r  r0   rK   )rÄ   r
  rE   )r”   r$   rs   r»   r   ÚENABLING_REQUIRED_SERVICErG   r:   rÇ   r    ÚmsgÚERROR_ENABLING_REQUIRED_SERVICE)r(   r¶   r™   r  rÆ   rÂ   Ú	error_msgr  r)   r)   r*   r¾     s&   ÿþÿø
z'UAEntitlement._enable_required_servicesÚignore_dependent_servicesc                 C   sº   |   ¡ \}}|tjkrdttjtjj| jd�d�fS |  	¡ \}}| j
r(|tjkr7dttjtjj| jd�d�fS | jrG|sG|  ¡ rGdttjƒfS | js[| jr[dttjtjj| jd�ƒfS dS )z»Report whether or not disabling is possible for the entitlement.

        :return:
            (True, None) if can disable
            (False, CanDisableFailure) if can't disable
        Frž   rŸ   rE   )rx   r   r©   r   r   ÚALREADY_DISABLEDr   rG   r:   r«   rB   r   r¬   ÚNOT_APPLICABLEÚCANNOT_DISABLE_NOT_APPLICABLEr]   Údetect_dependent_servicesÚACTIVE_DEPENDENT_SERVICESÚsupports_purger�   ÚPURGE_NOT_SUPPORTEDÚDISABLE_PURGE_NOT_SUPPORTED)r(   r  rx   r{   r«   r)   r)   r*   Úcan_disable=  sJ   	
þþÿ
ÿþþ

ÿþÿþþ
zUAEntitlement.can_disablec                 C   s˜   |  d| j d¡¡ |  ¡ \}}|s3|du rdS |jtjkr/|  |¡\}}|s.||_d|fS nd|fS |  	|¡s:dS |  
¡ s@dS |  d| j d¡¡ dS )a™  Disable specific entitlement

        @param silent: Boolean set True to silence print/log of messages

        @return: tuple of (success, optional reason)
            (True, None) on success.
            (False, reason) otherwise. reason is only non-None if it is a
                populated CanDisableFailure reason. This may expand to
                include other types of reasons in the future.
        r·   Úpre_disableNr¹   FÚpost_disablerE   )r»   r€   rC   r%  r¼   r   r!  Ú_disable_dependent_servicesr    Ú_perform_disabler  )r(   r¶   r%  rÂ   rÆ   r  r)   r)   r*   r  |  s(   ÿþ
zUAEntitlement.disablec                 C   r2   )a\  
        Disable specific entitlement. This should be implemented by subclasses.
        This method does the actual disable, and does not check can_disable
        or handle pre_disable or post_disable messaging.

        @param silent: Boolean set True to silence print/log of messages

        @return: True on success, False otherwise.
        Nr)   r  r)   r)   r*   r)  ¦  s   zUAEntitlement._perform_disablec                 C   r  )z¶
        Check for depedent services.

        :return:
            True if there are dependent services enabled
            False if there are no dependent services enabled
        r   )rl   r›   r3   r)   r)   r*   r   ³  r  z'UAEntitlement.detect_dependent_servicesc                 C   s:   g }| j D ]}|| jƒ ¡ \}}|tjkr| |¡ q|S )zo
        Return list of depedent services that must be disabled
        before disabling this service.
        )r]   rs   rx   r   ry   r8   )r(   ÚblockingÚdependent_service_clsr  r{   r)   r)   r*   r›   ½  s   
ÿþ

€z)UAEntitlement.blocking_dependent_servicesc                 C   sˆ   |   ¡ D ]=}|| jd�}| dtjj|jd�¡ | |¡\}}|sAd}|r2|jr2|jj	r2d|jj	 }tj
j||jd�}d|f  S qdS )	ay  
        Disable dependent services

        When performing a disable operation, we might have
        other services that depend on the original services.
        If that is true, we will alert the user about this
        and prompt for confirmation to disable these services
        as well.

        @param silent: Boolean set True to silence print/log of messages
        r  rÈ   )r™   r0   rK   )rÄ   r™   FrE   )r›   rs   r»   r   ÚDISABLING_DEPENDENT_SERVICErG   r:   r  r    r  Ú"FAILED_DISABLING_DEPENDENT_SERVICE)r(   r¶   r+  r  rÆ   rÂ   r  r  r)   r)   r*   r(  Ì  s&   ÿþÿø
z)UAEntitlement._disable_dependent_servicesc                 C   r2   )z=Check if system needs to be rebooted because of this service.Fr)   r3   r)   r)   r*   Ú_check_for_rebootñ  rU   zUAEntitlement._check_for_rebootÚ	operationÚsilentc                 C   s,   |   ¡ r|st tjj|d�¡ dS dS dS )zËCheck if user should be alerted that a reboot must be performed.

        @param operation: The operation being executed.
        @param silent: Boolean set True to silence print/log of messages
        )r/  N)r.  rã   rÈ   r   ÚENABLE_REBOOT_REQUIRED_TMPLrG   )r(   r/  r0  r)   r)   r*   Ú_check_for_reboot_msgõ  s   ÿÿÿz#UAEntitlement._check_for_reboot_msgc                 C   s*  | j }|stjtjfS | jD ]\}}}|ƒ |krtj|f  S q|d  di ¡}| dd¡}| jrR|durRt	 
¡ |vrRt |¡}tjtjj| jt	 
¡ d |¡d�fS | dd¡}| jru|durut	 ¡ j|vrutjtjj| jt	 ¡ jd�fS t	 ¡ }	| d	d¡}
| d
d¡}| jr¢|
dur¢|	j|
vr¢tjtjj| j|	jd |
¡d�fS | jrû|rû|	jdurû|	jdurûtjj| j|	j|d�}z| d¡\}}t |ƒ}t |ƒ}W n t!yá   t" #d|¡ tj|f Y S w |	j|k rìtj|fS |	j|krû|	j|k rûtj|fS | di ¡}|  $|¡\}}|�stj|fS tjdfS )aÈ  Check all contract affordances to vet current platform

        Affordances are a list of support constraints for the entitlement.
        Examples include a list of supported series, architectures for kernel
        revisions.

        :return:
            tuple of (ApplicabilityStatus, NamedMessage). APPLICABLE if
            platform passes all defined affordances, INAPPLICABLE if it doesn't
            meet all of the provided constraints.
        r$   r=   ÚarchitecturesNz, )r:   ÚarchÚsupported_archesÚseries)r:   r6  ÚkernelFlavorsÚminKernelVersion)r:   ÚkernelÚsupported_kernels)r:   r9  Ú
min_kernelÚ.z$Could not parse minKernelVersion: %sÚplatformChecks)%rB   r   Ú
APPLICABLEr   Ú"NO_ENTITLEMENT_AFFORDANCES_CHECKEDrT   r¬   rC   Úaffordance_check_archr   Úget_dpkg_archr   Údeduplicate_archesÚINAPPLICABLE_ARCHrG   r:   rO   Úaffordance_check_seriesÚget_release_infor6  ÚINAPPLICABLE_SERIESÚpretty_versionÚget_kernel_infoÚaffordance_check_kernel_flavorÚflavorÚINAPPLICABLE_KERNELÚuname_releaseÚ#affordance_check_kernel_min_versionÚmajorÚminorÚINAPPLICABLE_KERNEL_VERÚsplitÚintÚ
ValueErrorr¢   rß   rF   )r(   rB   Úerror_messageÚfunctorÚexpected_resultr=   Úaffordance_archesÚdeduplicated_archesÚaffordance_seriesÚkernel_infoÚaffordance_kernelsÚaffordance_min_kernelÚinvalid_msgÚkernel_majorÚkernel_minorÚmin_kern_majorÚmin_kern_minorÚaffordances_platform_checkrÆ   r¼   r)   r)   r*   r«     s    þ
ÿÿ
ýþÿþþÿ
ýþ	ÿþ

ýþû






z"UAEntitlement.applicability_statusc                 C   s6   t | jƒjs	tjS | j}|r|d  d¡rtjS tjS )z=Return whether the user is entitled to the entitlement or notr$   Úentitled)r   rs   Úis_attachedr   r¨   rB   rC   r¦   rŒ   r)   r)   r*   r¥   m  s   zUAEntitlement.contract_statusc                 C   sÂ   |   ¡ \}}|tjkrtj|fS | j}|s tjtjj	| j
d�fS |d  dd¡du r5tjtjj	| j
d�fS |  ¡ \}}|tjkrEtj|fS |tjkrOtj|fS |  ¡ \}}|r\tj|fS tj|fS )z4Return (user-facing status, details) for entitlementrž   r$   rc  F)r«   r   r>  r   r¬   rB   ÚUNAVAILABLEr   ÚSERVICE_NOT_ENTITLEDrG   r:   rC   rx   r   r©   ÚINACTIVEr  Úenabled_warning_statusÚACTIVE)r(   Úapplicabilityr´   rB   rx   Úexplanationrß   Úwarn_msgr)   r)   r*   Úuser_facing_statusv  s*   

þþ





z UAEntitlement.user_facing_statusc                 C   r2   )z›
        The current status of application of this entitlement

        :return:
            A tuple of (ApplicationStatus, human-friendly reason)
        Nr)   r3   r)   r)   r*   rx   —  ó   
z UAEntitlement.application_statusc                 C   r2   )zÜ
        If the entitlment is enabled, are there any warnings?
        The message is displayed as a Warning Notice in status output

        :return:
            A tuple of (warning bool, human-friendly reason)
        r¹   r)   r3   r)   r)   r*   rh  £  rn  z$UAEntitlement.enabled_warning_statusc                 C   s   d S r'   r)   r3   r)   r)   r*   Ústatus_description_override¯  r5   z)UAEntitlement.status_description_overridec                 C   s4   | j  d¡}|s
dS t |d¡}|t ¡ krdS dS )z<Return entitlement access info as stale and needing refresh.ÚexpiresFz%Y-%m-%dT%H:%M:%S.%fZT)rB   rC   r   ÚstrptimeÚutcnow)r(   Ú
expire_strÚexpiryr)   r)   r*   r¡   ´  s   zUAEntitlement.is_access_expiredc                 C   sh   t  ¡ }|du rtjS | dg ¡}|D ]}| d¡| jkr0| d¡}|dkr+tj  S tj  S qtjS )z6Check on the state of application on the status cache.NÚservicesr6   rz   Úenabled)r    Úreadr   r©   rC   r6   ry   )r(   Ústatus_cacheÚservices_status_listr
  Úservice_statusr)   r)   r*   Ú"_check_application_status_on_cache¿  s   


úz0UAEntitlement._check_application_status_on_cacheÚobligationsÚresourceTokenc                 C   s   t | d¡o|ƒS )NÚenableByDefault)ÚboolrC   )r(   r|  r}  r)   r)   r*   Ú_should_enable_by_defaultÓ  s   z'UAEntitlement._should_enable_by_defaultrŠ   ÚdeltasÚallow_enableÚverbosec                 C   sä  |sdS |  di ¡}|  di ¡}t ¡ }t|tjkƒ}|s7|r(t |¡ |d }|r7d|v r7|d dtjfv }|r�|rB|rB|  ¡ }	n|  	¡ \}	}
|	t
jkrŽ|  ¡ \}}|rrt d| j¡ |  t ¡ ¡ |rpt tjj| jd�¡ dS |rw|jnd}t d	| j|¡ |rŽt tjj| jd�¡ dS |  d
¡}|sœ|  d
¡}|  di ¡}|  ||¡}|  ¡ \}}
|rð|rð|rÜtjj| jd�}|rÆtj|tjd� |  t ¡ ¡ |rÚt tj j| j!d�¡ dS |rîtj"j| jd�}tj|tjd� dS dS )a¯  Process any contract access deltas for this entitlement.

        :param orig_access: Dictionary containing the original
            resourceEntitlement access details.
        :param deltas: Dictionary which contains only the changed access keys
        and values.
        :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 verbose: If True, display output to stdout

        :return: True when delta operations are processed; False when noop.
        :raise: UbuntuProError when auto-enable fails unexpectedly.
        Tr$   r�   rc  Fz3Disabling %s after refresh transition to unentitledr  r0   zDCannot disable %s after refresh transition to unentitled.
Reason: %sr}  r|  rò   )Ú	file_typerž   )#rC   r    rw  r  r   ÚDROPPED_KEYr   r‹   r{  rx   r   r©   r%  r¢   rÈ   r6   r  r   ÚProgressWrapperrã   r   ÚDISABLE_DURING_CONTRACT_REFRESHrG   Úmessage_valuerß   Ú)UNABLE_TO_DISABLE_DURING_CONTRACT_REFRESHr€  rµ   ÚENABLE_BY_DEFAULT_TMPLÚsysÚstderrrÇ   ÚENABLED_TMPLr:   ÚENABLE_BY_DEFAULT_MANUAL_TMPL)r(   rŠ   r�  r‚  rƒ  Údelta_entitlementÚdelta_directivesrx  Útransition_to_unentitledrx   r{   r%  rÂ   Úfail_msgr}  Údelta_obligationsÚenable_by_defaultrµ   r  r)   r)   r*   Úprocess_contract_deltasØ  sŽ   
þ

þÿÿòüÿÿ

ÿûÿz%UAEntitlement.process_contract_deltasc                 C   s8   | j rd S | dtjjdd�¡ t t ¡ ¡ d| _ d S )NrÈ   zstandard Ubunturò   T)r†   r»   r   ÚAPT_UPDATING_LISTrG   r   Úupdate_sources_listÚget_system_sources_filer  r)   r)   r*   rþ   @  s   ÿ
z"UAEntitlement._update_sources_list)Nr0   FFN)F)FT)hr,   r-   r.   r6   Úhelp_doc_urlr±   r"  rL   rW   rZ   r\   r@  rD  rM  rI  r?   ÚpropertyÚstrr4   r   r9   ÚabcÚabstractmethodr:   r<   r7   r   r   r   r  r   r   r/   rF   rS   r"   rT   r#   rX   r[   r	   r]   r_   r   rh   ro   rM   rr   r|   r}   r   r!   r€   r   rƒ   r+   rd   rB   rR  r�   r�   rš   r�   r   rµ   r   r†  r
   rÇ   r¿   rü   rÀ   r  rÁ   r“   r­   r½   r¯   r”   r¾   r   r%  r  r)  r   r›   r(  r.  r2  r   r«   r   r¥   r   rm  r   rx   rh  ro  r¡   r{  r€  r•  rþ   r)   r)   r)   r*   r%   2   sb   
ÿ
þ
		
	
úþýüû
ú
ù
Jþ
ý=W%

þ
ý.
þ
ý!ÿÿ
þ?ÿ
þ*
ÿ
þ%ÿÿÿ
þ
þi	
þ!þ
þ
þ
ÿÿ
þ	û
þ
ýüû
úhr%   )Ú	metaclass)5rœ  r‡   Úloggingr‹  r   Útypingr   r   r   r   r   r   r	   r
   Úuaclientr   r   r   r   r   r   r   r   r   r   r   Ú(uaclient.api.u.pro.status.is_attached.v1r   Ú(uaclient.entitlements.entitlement_statusr   r   r   r   r   r   r   r   Úuaclient.filesr   Úuaclient.files.state_filesr    Úuaclient.typesr!   r"   Úget_event_loggerrã   Ú	getLoggerÚreplace_top_level_logger_namer,   r¢   r#   ÚABCMetar%   r)   r)   r)   r*   Ú<module>   s     (4(

