U
    lHJe/                     @   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 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& d dl'm(Z( e) Z*e+e,e-Z.G d	d
 d
Z/G dd de j0dZ1dS )    N)datetime)AnyDictListOptionalSetTupleTypeUnion)
aptconfigcontractevent_logger
exceptionshttpmessagessnapsystemutil)_is_attached)ApplicabilityStatusApplicationStatusCanDisableFailureCanDisableFailureReasonCanEnableFailureCanEnableFailureReasonContractStatusUserFacingStatus)MessagingOperationsDictStaticAffordance)is_config_value_truec                   @   s"   e Zd Zed ejdddZdS )IncompatibleServiceUAEntitlemententitlement	named_msgc                 C   s   || _ || _d S Nr#   )selfr$   r%    r(   </usr/lib/python3/dist-packages/uaclient/entitlements/base.py__init__'   s    zIncompatibleService.__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dZeejedddZeedd	d
Zeee dddZeejedddZeejedddZeedddZeeef eee e!j" f dddZ#eedddZ$eee%df dddZ&eee'df dddZ(eee)d  df dddZ*eee)d  df ddd Z+eee)d  f dd!d"Z,e-e dd#d$Z.eee)d  f dd%d&Z/eeee)d  f dd'd(Z0eeee)d  f dd)d*Z1ee d  dd+d,Z2ee3dd-d.Z4dwe e5j6 eeeeee ee  dd/d0d1Z7ed2d3 Z8d4d5 Z9ed6d7 Z:eee e; f dd8d9Z<dxeeee=de;f f d:d;d<Z>edd=d>Z?edd?d@Z@eddAdBZAejdyeed:dCdDZBeddEdFZCdGdH ZDee' ddIdJZEeddKdLZFeee e!j" f ddMdNZGeee e!j" f ddOdPZHdzeeee eI f dQdRdSZJd{eeee eI f d:dTdUZKejd|eed:dVdWZLeeee e!j" f d:dXdYZMeddZd[ZNd}eedd\d]d^ZOeePe e!j" f dd_d`ZQeRddadbZSeeTe e!j" f ddcddZUejeeVe e!j" f ddedfZWeee e!j" f ddgdhZXe e ddidjZYeddkdlZZeVddmdnZ[eeef e e edodpdqZ\d~eeef eeef eedrdsdtZ]dudv Z^dS )r"   NF r(   T)returnc                 C   s   dS )z&The lowercase name of this entitlementNr(   r'   r(   r(   r)   nameT   s    zUAEntitlement.namec                 C   s   dS )z?The lowercase name of this entitlement, in case it is a variantr/   r(   r1   r(   r(   r)   variant_nameZ   s    zUAEntitlement.variant_namec                 C   s$   | j g}| j| j kr || j |S )z1The list of names this entitlement may be called.)r2   presentation_nameappend)r'   valid_namesr(   r(   r)   r6   _   s    zUAEntitlement.valid_namesc                 C   s   dS )z,The human readable title of this entitlementNr(   r1   r(   r(   r)   titleg   s    zUAEntitlement.titlec                 C   s   dS )z&A sentence describing this entitlementNr(   r1   r(   r(   r)   descriptionm   s    zUAEntitlement.descriptionc                 C   s@   | j r| jS | jjjr6| jdi di d| jS | jS dS )z/The user-facing name shown for this entitlementr$   affordancesZpresentedAsN)
is_variantr3   cfgmachine_token_fileZ
is_presententitlement_cfggetr2   r1   r(   r(   r)   r4   s   s    
  zUAEntitlement.presentation_name)platform_checkr0   c                 C   s   dS )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'   r?   r(   r(   r)   verify_platform_checks   s    z$UAEntitlement.verify_platform_checksc                 C   sF   | j }| jrBd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
  * {}: {})formatr8   ).0r3   variant_clsr(   r(   r)   
<listcomp>   s   z+UAEntitlement.help_info.<locals>.<listcomp>
z

)	help_textvariantsitemsjoinr   ZCLI_HELP_VARIANTS_HEADER)r'   rG   Zvariant_itemsZvariant_textr(   r(   r)   	help_info   s    zUAEntitlement.help_info.c                 C   s   dS )Nr(   r(   r1   r(   r(   r)   static_affordances   s    z UAEntitlement.static_affordancesc                 C   s   | 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_servicesr1   r(   r(   r)   incompatible_services   s    z#UAEntitlement.incompatible_servicesc                 C   s   | j S )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_servicesr1   r(   r(   r)   required_services   s    zUAEntitlement.required_servicesc                 C   s   | j S )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_servicesr1   r(   r(   r)   dependent_services   s    	z UAEntitlement.dependent_servicesc                 C   s   i S r&   r(   r1   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$   	overridesZselectorvariant)set_base_entitlement_cfgr>   add)r'   valid_variantsr=   rT   overriderU   r(   r(   r)   _get_contract_variants   s    z$UAEntitlement._get_contract_variantsc                 C   s`   |   }|  }d|kr&d|d i}ni }t|D ]}||kr2|| ||< q2t|dkr\|S i S )Ngeneric   )rS   r[   sortedlen)r'   Zservice_variantsZcontract_variantsrY   rU   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:   r`   r1   r(   r(   r)   rH      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(   )r3   )rC   r2   clsr1   r(   r)   
<dictcomp>   s   
 z0UAEntitlement.other_variants.<locals>.<dictcomp>)r:   r`   rI   r1   r(   r1   r)   other_variants   s
    

zUAEntitlement.other_variantsc                 C   sZ   | j  D ]J}|jdkrq
|| j| j| 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)
        r\   )r;   
assume_yes
allow_betacalled_nameaccess_onlyN)rH   valuesr3   r;   rd   re   _called_namerg   application_statusr   ENABLED)r'   rD   rU   status_r(   r(   r)   enabled_variant   s    


zUAEntitlement.enabled_variantc                 C   s   i S r&   r(   r1   r(   r(   r)   	messaging  s    zUAEntitlement.messaging)r;   rd   re   rf   rg   purge
extra_argsr0   c                 C   sV   |st  }|| _|| _|| _|| _|| _|dk	r:|| _ng | _|| _d| _	d| _
dS )z]Setup UAEntitlement instance

        @param config: Parsed configuration dictionary
        NF)r   UAConfigr;   rd   re   rg   rp   rq   ri   _valid_service_is_sources_list_updated)r'   r;   rd   re   rf   rg   rp   rq   r(   r(   r)   r*     s    zUAEntitlement.__init__c                 C   s.   | j dkr(| j p$| jp$t| jjd| _ | j S )z2Check if the service is marked as valid (non-beta)Nzfeatures.allow_beta)rs   is_betare   r    r;   r1   r(   r(   r)   valid_service5  s    
zUAEntitlement.valid_servicec                 C   s   t | jjj| ji S r&   )copydeepcopyr;   r<   Zentitlementsr>   r2   r1   r(   r(   r)   rW   A  s    z#UAEntitlement._base_entitlement_cfgc                 C   s*   |   }| jr|s|S tj|| jd |S )N)orig_accessrU   )rW   r:   r   apply_contract_overridesr3   r'   r=   r(   r(   r)   r=   F  s    
 zUAEntitlement.entitlement_cfgc                 C   s&  |   r"td| j t| j |  tj	ksNdt
tjtjj| jddfS |  \}}|tjkrdt
tjtjj| jddfS | jsdt
tjfS |  \}}|tjkrdt
tj|dfS | jr|  rdt
tjfS | jr|  sd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r7   messager@   )$is_access_expiredLOGdebugr2   r   Zrefreshr;   contract_statusr   ENTITLEDr   r   ZNOT_ENTITLEDr   
UNENTITLEDrB   r7   rj   r   DISABLEDZALREADY_ENABLEDrv   ZIS_BETAapplicability_statusr   INAPPLICABLErN   detect_incompatible_servicesINCOMPATIBLE_SERVICErP   check_required_services_activeINACTIVE_REQUIRED_SERVICESsupports_access_onlyrg   ZACCESS_ONLY_NOT_SUPPORTEDZ ENABLE_ACCESS_ONLY_NOT_SUPPORTED)r'   rj   rm   r   detailsr(   r(   r)   
can_enableS  sh    	

 
zUAEntitlement.can_enable)silentr0   c           	      C   s  | j dg }t|sdS |  \}}|s|dkr8dS |jtjkrd|  \}}|s||_	d|fS n4|jtj
kr|  \}}|s||_	d|fS nd|fS | j dg }t|sdS | js|  sdS |  sdS | j|d}|sdS | j dg }t|sd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.
        Zpre_can_enableFNNFZ
pre_enabler   Zpost_enabler@   )ro   r>   r   handle_message_operationsr   reasonr   r   handle_incompatible_servicesr~   r   _enable_required_servicesrg   handle_required_snapshandle_required_packages_perform_enable)	r'   r   msg_opsr   failZincompat_reterrorZreq_retretr(   r(   r)   enable  sH    



zUAEntitlement.enablec           	   
   C   s  | j di di d}|dkr(dS t sLttjjdd t	  t
 sttjjdd ztd W nF tjk
r } z&tjd	|d
 ttjjdd W 5 d}~X Y nX t  td| jjtj}td| jjtj}tj||tjd |rttj t|dd dD ]p}|d }zt| W nR tjk
r   |dd}|d}ttjj|d tj|||d Y nX q"dS )z. "install snaps necessary to enable a service.r$   
directivesZrequiredSnapsNTZsnapdZpackagesz
snapd snapz!Failed to install snapd as a snap)exc_infozsnap install snapd)Zcommandr   Zhttps)
http_proxyhttps_proxyZretry_sleepsc                 S   s
   |  dS )Nr2   r>   )xr(   r(   r)   <lambda>      z5UAEntitlement.handle_required_snaps.<locals>.<lambda>)keyr2   ZclassicConfinementSupportFchannel)r   )r   classic_confinement_support) r=   r>   r   Zis_snapd_installedeventinfor   INSTALLING_PACKAGESrB   Zinstall_snapdZis_snapd_installed_as_a_snapZinstall_snapr   ZProcessExecutionErrorr   warningZEXECUTING_COMMAND_FAILEDZrun_snapd_wait_cmdr   Zvalidate_proxyr;   r   ZPROXY_VALIDATION_SNAP_HTTP_URLr   ZPROXY_VALIDATION_SNAP_HTTPS_URLZconfigure_snap_proxyZSNAP_INSTALL_RETRIESZINSTALLING_REQUIRED_SNAPSr^   Zget_snap_infoZSnapNotInstalledErrorZ INSTALLING_REQUIRED_SNAP_PACKAGE)	r'   Zrequired_snapser   r   Zsnap_pkgZ	snap_namer   r   r(   r(   r)   r     s          
z#UAEntitlement.handle_required_snapsc                 C   sn   | j di di d}|s$dS |   dd |D }td| ttjj	d
|d	 t| dS )
/install packages necessary to enable a service.r$   r   requiredPackagesTc                 S   s   g | ]}|d  qS r2   r(   rC   packager(   r(   r)   rE   8  s     z:UAEntitlement.handle_required_packages.<locals>.<listcomp>zInstalling packages %r r   )r=   r>   _update_sources_listr   r   r   r   r   r   rB   rJ   r   Zrun_apt_install_command)r'   required_packagespackage_namesr(   r(   r)   r   )  s&     
z&UAEntitlement.handle_required_packagesc                 C   sv   | j di di d}|s$dS dd |D }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 )ZremoveOnDisableFr2   r   r   r(   r(   r)   rE   P  s   zCUAEntitlement.handle_removing_required_packages.<locals>.<listcomp>zUninstalling packages %rr   r   )r=   r>   r   r   rJ   r   r   r   ZUNINSTALLING_PACKAGESrB   r   Zremove_packagesZUNINSTALLING_PACKAGES_FAILED)r'   r   r   Zpackage_names_strr(   r(   r)   !handle_removing_required_packagesC  s0     
z/UAEntitlement.handle_removing_required_packagesc                 C   s   dS )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   c  s    	zUAEntitlement._perform_enablec                 C   s2   | j D ]&}|| j \}}|tjkr dS qdS )z
        Check for depedent services.

        :return:
            True if there are dependent services enabled
            False if there are no dependent services enabled
        TF)rR   r;   rj   r   rk   )r'   dependent_service_cls
ent_statusrm   r(   r(   r)   detect_dependent_servicesn  s    

z'UAEntitlement.detect_dependent_servicesc                 C   s2   | j D ]&}|| j \}}|tjkr dS qd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
        FT)rP   r;   rj   r   rk   )r'   required_service_clsr   rm   r(   r(   r)   r     s
    

z,UAEntitlement.check_required_services_activec                 C   s<   g }| j D ],}|| j \}}|tjkr
|| q
|S )zI
        :return: List of incompatible services that are enabled
        )rN   r$   r;   rj   r   rk   r5   )r'   r   servicer   rm   r(   r(   r)   blocking_incompatible_services  s    

z,UAEntitlement.blocking_incompatible_servicesc                 C   s   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   )r_   r   r1   r(   r(   r)   r     s    z*UAEntitlement.detect_incompatible_servicesc                 C   s   t j| jjdd}|  D ]}|j| jdd}tjj| j|jd}tj	j| j|jd}|rfd|f  S t j
|| jdsd|f  S ttjj|jd |jdd	}|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   Zpath_to_valueT)rd   )service_being_enabledZincompatible_serviceFmsgrd   r   r   Nr@   )r   r    r;   r   r$   r   r   rB   r7   Z!INCOMPATIBLE_SERVICE_STOPS_ENABLEprompt_for_confirmationrd   r   r   ZDISABLING_INCOMPATIBLE_SERVICEdisable)r'   Zcfg_block_disable_on_enabler   entuser_msge_msgr   r(   r(   r)   r     s<     z*UAEntitlement.handle_incompatible_servicesc           
      C   s   | j D ]}|| jdd}| d tjk}|rtjj| j|jd}tj	j| j|jd}t
j|| jdsrd|f  S ttjj|jd |jdd\}}|sd	}|r|jr|jjrd
|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.
        T)re   r   )r   required_servicer   Fr   r   r/   rF   )r   r   r@   )rP   r;   rj   r   r   r   ZREQUIRED_SERVICErB   r7   ZREQUIRED_SERVICE_STOPS_ENABLEr   r   rd   r   r   ZENABLING_REQUIRED_SERVICEr   r~   r   ZERROR_ENABLING_REQUIRED_SERVICE)
r'   r   r   Zis_service_disabledr   r   r   r   	error_msgr   r(   r(   r)   r     sD    

  z'UAEntitlement._enable_required_services)ignore_dependent_servicesr0   c                 C   s   |   \}}|tjkr4dttjtjj| jddfS | j	rT|sT| 
 rTd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}   r@   )rj   r   r   r   r   ZALREADY_DISABLEDr   rB   r7   rR   r   ACTIVE_DEPENDENT_SERVICESsupports_purgerp   ZPURGE_NOT_SUPPORTEDZDISABLE_PURGE_NOT_SUPPORTED)r'   r   rj   rm   r(   r(   r)   can_disable  s2    	


zUAEntitlement.can_disablec                 C   s   | j dg }t|sdS |  \}}|sp|dkr8dS |jtjkrh| j|d\}}|sp||_	d|fS nd|fS | j
|dsdS |  sdS | j dg }t|sdS | jd|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.
        Zpre_disabler   Nr   FZpost_disablezdisable operation)	operationr   r@   )ro   r>   r   r   r   r   r   r   _disable_dependent_servicesr~   _perform_disabler   _check_for_reboot_msg)r'   r   r   r   r   r   r   r(   r(   r)   r   7  s8    


 zUAEntitlement.disablec                 C   s   dS )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   h  s    zUAEntitlement._perform_disablec                 C   s   | j D ]}|| jdd}| d tjk}|rtjj|j| jd}tj	j| j|jd}t
j|| jdsrd|f  S |sttjj|jd |jdd	\}}|sd
}	|r|jr|jjrd|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
        T)r;   rd   r   )dependent_serviceservice_being_disabled)r   r   r   F)r   r   r/   rF   )r   r   r@   )rR   r;   rj   r   rk   r   ZDEPENDENT_SERVICErB   r7   ZDEPENDENT_SERVICE_STOPS_DISABLEr   r   rd   r   r   ZDISABLING_DEPENDENT_SERVICEr   r~   r   Z"FAILED_DISABLING_DEPENDENT_SERVICE)r'   r   r   r   Zis_service_enabledr   r   r   r   r   r   r(   r(   r)   r   u  sF    
  z)UAEntitlement._disable_dependent_servicesc                 C   s   t  S )z%Check if system needs to be rebooted.)r   Zshould_rebootr1   r(   r(   r)   _check_for_reboot  s    zUAEntitlement._check_for_reboot)r   r   r0   c                 C   s$   |   r |s ttjj|d 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   ZENABLE_REBOOT_REQUIRED_TMPLrB   )r'   r   r   r(   r(   r)   r     s    z#UAEntitlement._check_for_reboot_msgc                 C   sB  | j }|stjtjfS | jD ]"\}}}| |krtj|f  S q|d di }|dd}| jr|dk	rt	
 |krt|}tjtjj| jt	
 d|dfS |dd}| jr|dk	rt	 j|krtjtjj| jt	 jdfS t	 }	|d	d}
|d
d}| jrJ|
dk	rJ|	j|
krJtjtjj| j|	jd|
dfS | jr|r|	jdk	r|	jdk	rtjj| j|	j|d}z"|d\}}t |}t |}W n, t!k
r   t"#d| tj|f Y S X |	j|k rtj|fS |	j|kr|	j|k rtj|fS |di }| $|\}}|s8t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$   r9   ZarchitecturesNz, )r7   ZarchZsupported_archesseries)r7   r   ZkernelFlavorsZminKernelVersion)r7   kernelZsupported_kernels)r7   r   Z
min_kernel.z$Could not parse minKernelVersion: %sZplatformChecks)%r=   r   
APPLICABLEr   Z"NO_ENTITLEMENT_AFFORDANCES_CHECKEDrL   r   r>   affordance_check_archr   Zget_dpkg_archr   Zdeduplicate_archesZINAPPLICABLE_ARCHrB   r7   rJ   affordance_check_seriesZget_release_infor   ZINAPPLICABLE_SERIESZpretty_versionZget_kernel_infoaffordance_check_kernel_flavorZflavorZINAPPLICABLE_KERNELZuname_release#affordance_check_kernel_min_versionmajorminorZINAPPLICABLE_KERNEL_VERsplitint
ValueErrorr   r   rA   )r'   r=   Zerror_messageZfunctorZexpected_resultr9   Zaffordance_archesZdeduplicated_archesZaffordance_seriesZkernel_infoZaffordance_kernelsZaffordance_min_kernelZinvalid_msgZkernel_majorZkernel_minorZmin_kern_majorZmin_kern_minorZaffordances_platform_checkr   r   r(   r(   r)   r     s    


	


z"UAEntitlement.applicability_statusc                 C   s6   t | jjstjS | j}|r0|d dr0tjS tjS )z=Return whether the user is entitled to the entitlement or notr$   entitled)r   r;   Zis_attachedr   r   r=   r>   r   r{   r(   r(   r)   r   *  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krjtjtjj	| j
dfS |  \}}|tjkrtj|fS |  \}}|rtj|fS tj|fS )z4Return (user-facing status, details) for entitlementr|   r$   r   F)r   r   r   r   r   r=   ZUNAVAILABLEr   ZSERVICE_NOT_ENTITLEDrB   r7   r>   rj   r   r   ZINACTIVEenabled_warning_statusZWARNINGZACTIVE)r'   Zapplicabilityr   r=   rj   Zexplanationr   Zwarn_msgr(   r(   r)   user_facing_status3  s&    




z UAEntitlement.user_facing_statusc                 C   s   dS )z
        The current status of application of this entitlement

        :return:
            A tuple of (ApplicationStatus, human-friendly reason)
        Nr(   r1   r(   r(   r)   rj   R  s    
z UAEntitlement.application_statusc                 C   s   dS )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(   r1   r(   r(   r)   r   ^  s    
z$UAEntitlement.enabled_warning_statusc                 C   s   d S r&   r(   r1   r(   r(   r)   status_description_overridej  s    z)UAEntitlement.status_description_overridec                 C   s4   | j d}|sdS t|d}|t kr0dS dS )z<Return entitlement access info as stale and needing refresh.ZexpiresFz%Y-%m-%dT%H:%M:%S.%fZT)r=   r>   r   strptimeZutcnow)r'   Z
expire_strZexpiryr(   r(   r)   r   o  s    zUAEntitlement.is_access_expiredc                 C   sl   | j d}|dkrtjS |dg }|D ]:}|d| jkr*|d}|dkrZtj  S tj  S q*tjS )z6Check on the state of application on the status cache.status-cacheNservicesr2   rl   enabled)r;   
read_cacher   r   r>   r2   rk   )r'   status_cacheZservices_status_listr   Zservice_statusr(   r(   r)   "_check_application_status_on_cachez  s    

z0UAEntitlement._check_application_status_on_cache)obligationsresourceTokenr0   c                 C   s   t |do|S )NZenableByDefault)boolr>   )r'   r   r   r(   r(   r)   _should_enable_by_default  s    z'UAEntitlement._should_enable_by_default)ry   deltasallow_enabler0   c                 C   s  |sdS | di }| di }| jd}t|tjk}|sr|rTt| |d }|rrd|krr|d dtjfk}|r|r|r|  }n| 	 \}}	|t
jkr|  rtd |   d| j}
ttjj| jd	 n td
 ttjj| jd	 | jd| j dS | d}|s0| d}| di }| ||}|rTd| _|  \}}	|r|r|rtjj| jd}
tj|
tjd |   n 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   r   r   Fz3Disabling %s after refresh transition to unentitledz.Due to contract refresh, '{}' is now disabled.r   z8Cannot disable %s after refresh transition to unentitledzmachine-access-{}r   r   r   )Z	file_type) r>   r;   r   r   r   ZDROPPED_KEYr   rz   r   rj   r   r   r   r   r   r   rB   r2   r   r   ZDISABLE_DURING_CONTRACT_REFRESHr   Z)UNABLE_TO_DISABLE_DURING_CONTRACT_REFRESHZdelete_cache_keyr   re   r   ZENABLE_BY_DEFAULT_TMPLsysstderrr   ZENABLE_BY_DEFAULT_MANUAL_TMPL)r'   ry   r   r   Zdelta_entitlementZdelta_directivesr   Ztransition_to_unentitledrj   rm   r   r   Zdelta_obligationsZenable_by_defaultr   r(   r(   r)   process_contract_deltas  s    




 
z%UAEntitlement.process_contract_deltasc                 C   s2   | j r
d S ttjjdd td d| _ d S )Nzstandard Ubuntur   z/etc/apt/sources.listT)rt   r   r   r   ZAPT_UPDATING_LISTrB   r   Zupdate_sources_listr1   r(   r(   r)   r     s
    
z"UAEntitlement._update_sources_list)NFFr/   FFN)F)F)F)F)F)F)F)_r+   r,   r-   Zhelp_doc_urlrd   ru   r   r   rG   rM   rO   rQ   r   r   r   r   r:   propertyabcabstractmethodstrr2   r3   r   r6   r7   r8   r4   r   r   r   r   r   r   r.   rA   rK   r   rL   r!   rN   r	   rP   rR   rS   r   r[   r`   rH   rc   rn   r   ro   r   rr   r*   rv   rW   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   rj   r   r   r   r   r   r   r   r(   r(   r(   r)   r"   0   s  

		
	       


O AH 
84 + 19  i
 	 

cr"   )	metaclass)2r   rw   Zloggingr   r   typingr   r   r   r   r   r   r	   r
   Zuaclientr   r   r   r   r   r   r   r   r   r   Z(uaclient.api.u.pro.status.is_attached.v1r   Z(uaclient.entitlements.entitlement_statusr   r   r   r   r   r   r   r   Zuaclient.typesr   r   Zuaclient.utilr    Zget_event_loggerr   Z	getLoggerZreplace_top_level_logger_namer+   r   r!   ABCMetar"   r(   r(   r(   r)   <module>   s   (0(

