o
    ϴf˹                     @   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					dd1e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	dd_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	ddne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ddZddeeef dee defddZe	ddeeef deeef dedefddZfdFeAjBfdd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   )zVerify 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rd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 qw 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 )zReport 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 )zCheck 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rtjtjj| j|	jd|
dfS | jr|r|	jdur|	jdurtjj| j|	j|d}z|d\}}t |}t |}W n t!y   t"#d| tj|f Y S w |	j|k rtj|fS |	j|kr|	j|k rt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_enablec                 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|  \}
}|
rptd| j | t  ttjj| jd dS |ru|jnd}td	| j| ttjj| jd dS | d
}|s| d
}| di }| ||}|  \}}	|r|r|rtjj| jd}tj|tjd | t  ttj j| j!d dS tj"j| jd}tj|tjd dS dS )au  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.

        :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  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   8  s   
z"UAEntitlement._update_sources_list)Nr0   FFN)F)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   s\   


		
	



J
=W%


.

!
?
*

%

i	
!



	


`r%   )	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(

