o
    K&b                     @   s  d dl Z 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 d dlZd dl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  d dl!m"Z"m#Z# d dl$m%Z% d	Z&e' Z(G d
d dZ)G dd de j*dZ+dS )    N)datetime)AnyDictListOptionalTupleTypeUnion)configcontractevent_logger
exceptionsmessagesstatusutil)DEFAULT_HELP_FILE)ApplicabilityStatusCanDisableFailureCanDisableFailureReasonCanEnableFailureCanEnableFailureReasonContractStatusUserFacingStatus)MessagingOperationsDictStaticAffordance)is_config_value_truezZ(?P<major>[\d]+)[.-](?P<minor>[\d]+)[.-](?P<patch>[\d]+\-[\d]+)-(?P<flavor>[A-Za-z0-9_-]+)c                   @   s$   e Zd Zded dejfddZdS )IncompatibleService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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	e
ej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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f fddZe
defddZ				dZdeej  de!de!d eddf
d!d"Z"e
d#d$ Z#	d[d%e!dee!e$de%f f fd&d'Z&ejd[d%e!de!fd(d)Z'	d[d*e!dee!ee( f fd+d,Z)dee!ee% f fd-d.Z*d/eedf de!fd0d1Z+de!fd2d3Z,d4d5 Z-dee fd6d7Z.de!fd8d9Z/dee!ee0j1 f fd:d;Z2dee!ee0j1 f fd<d=Z3dee4ee0j1 f fd>d?Z5ejd[d%e!de!fd@dAZ6d%e!dee!ee0j1 f fdBdCZ7de!fdDdEZ8dFeddfdGdHZ9	d[d%e!dee!ee( f fdIdJZ:de;fdKdLZ<de!fdMdNZ=de>j?fdOdPZ@	d[dQeAeeBf dReAeeBf dSe!de!fdTdUZCdeeDee0j1 f fdVdWZEejdee>j?ee0j1 f fdXdYZFdS )\r   NFr"   returnc                 C      dS )z&The lowercase name of this entitlementNr"   r!   r"   r"   r#   nameJ      zUAEntitlement.namec                 C   s$   | j g}| j| j kr|| j |S )z1The list of names this entitlement may be called.)r,   presentation_nameappend)r!   valid_namesr"   r"   r#   r0   P   s   zUAEntitlement.valid_namesc                 C   r*   )z,The human readable title of this entitlementNr"   r+   r"   r"   r#   titleX   r-   zUAEntitlement.titlec                 C   r*   )z&A sentence describing this entitlementNr"   r+   r"   r"   r#   description^   r-   zUAEntitlement.descriptionc                 C   s,   | j j| ji di di d| jS )z/The user-facing name shown for this entitlementr   affordancesZpresentedAs)cfgentitlementsgetr,   r+   r"   r"   r#   r.   d   s
   
zUAEntitlement.presentation_namec                 C   sl   | j du r3i }tjtr'ttd}t|}W d   n1 s"w   Y  || j	i dd| _ | j S )z$Help information for the entitlementNrhelp )

_help_infoospathexistsr   openyamlZ	safe_loadr6   r,   )r!   Z	help_dictfr"   r"   r#   	help_infon   s   
zUAEntitlement.help_info.c                 C   r*   )Nr"   r"   r+   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_servicesr+   r"   r"   r#   incompatible_services      z#UAEntitlement.incompatible_servicesc                 C   rD   )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_servicesr+   r"   r"   r#   required_services   rG   zUAEntitlement.required_servicesc                 C   rD   )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_servicesr+   r"   r"   r#   dependent_services   s   	z UAEntitlement.dependent_servicesc                 C   s   i S r    r"   r+   r"   r"   r#   	messaging   rC   zUAEntitlement.messagingr9   r4   
assume_yes
allow_betacalled_namec                 C   s.   |st  }|| _|| _|| _|| _d| _dS )z]Setup UAEntitlement instance

        @param config: Parsed configuration dictionary
        N)r
   UAConfigr4   rM   rN   Z_called_name_valid_service)r!   r4   rM   rN   rO   r"   r"   r#   r$      s   
zUAEntitlement.__init__c                 C   s.   | j du 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)rQ   is_betarN   r   r4   r+   r"   r"   r#   valid_service   s   
zUAEntitlement.valid_servicesilentc           	      C   s   | j dg }t|sdS |  \}}|sL|du rdS |jtjkr2|  \}}|s1||_	d|fS n|jtj
krH|  \}}|sG||_	d|fS nd|fS | j|d}|sVdS | j dg }t|sdd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_enableFNNFrT   Zpost_enableTN)rL   r6   r   handle_message_operations
can_enablereasonr   INCOMPATIBLE_SERVICEhandle_incompatible_servicesmessageINACTIVE_REQUIRED_SERVICES_enable_required_services_perform_enable)	r!   rT   msg_opsrY   failZincompat_reterrorZreq_retretr"   r"   r#   enable   s<   

zUAEntitlement.enablec                 C   r*   )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!   rT   r"   r"   r#   r`      s   	zUAEntitlement._perform_enableignore_dependent_servicesc                 C   sZ   |   \}}|tjjkrdttjtjj| j	ddfS | j
r+|s+|  r+dttj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
        Fr1   r]   rW   )application_statusr   ApplicationStatusDISABLEDr   r   ZALREADY_DISABLEDr   formatr1   rK   detect_dependent_servicesACTIVE_DEPENDENT_SERVICES)r!   rg   rj   _r"   r"   r#   can_disable  s    	
zUAEntitlement.can_disablec                 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jkrBdt
tjtjj| jddfS | jsLdt
tjfS |  \}}|tjjkradt
tj|dfS | jro|  rodt
tjfS | jr}|  s}dt
tj 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' expiryFrh   ri   rW   )!is_access_expiredloggingdebugr,   r   Zrequest_updated_contractr4   contract_statusr   ENTITLEDr   r   ZNOT_ENTITLEDr   
UNENTITLEDrm   r1   rj   r   rk   rl   ZALREADY_ENABLEDrS   ZIS_BETAapplicability_statusr   INAPPLICABLErF   detect_incompatible_servicesr[   rI   check_required_services_activer^   )r!   rj   rp   rx   detailsr"   r"   r#   rY   $  sX   	zUAEntitlement.can_enableservicesc              	   C   sb   ddl m}m} |D ]$}z||}W n	 |y   Y q
w || j \}}|tjjkr. dS q
dS )Nr   )EntitlementNotFoundErrorentitlement_factoryTF)uaclient.entitlementsr~   r   r4   rj   r   rk   ENABLED)r!   r}   r~   r   serviceent_cls
ent_statusrp   r"   r"   r#   _check_any_service_is_activef  s   z*UAEntitlement._check_any_service_is_activec                 C   s   | j | jdS )z
        Check for depedent services.

        :return:
            True if there are dependent services enabled
            False if there are no dependent services enabled
        )r}   )r   rK   r+   r"   r"   r#   rn   w  s   z'UAEntitlement.detect_dependent_servicesc              	   C   sb   ddl m} | jD ]%}z||}|| j \}}|tjjkr#W  dS W q	 tj	y.   Y q	w 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
        r   r   FT)
r   r   rI   r4   rj   r   rk   r   r   r~   )r!   r   required_servicer   r   rp   r"   r"   r#   r{     s   
z,UAEntitlement.check_required_services_activec                 C   s>   g }| j D ]}|| j \}}|tjjkr|| q|S )zI
        :return: List of incompatible services that are enabled
        )rF   r   r4   rj   r   rk   r   r/   )r!   rd   r   r   rp   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   )lenr   r+   r"   r"   r#   rz     s   z*UAEntitlement.detect_incompatible_servicesc                 C   s   t j| jjdd}|  D ]I}|| j}tjj| j|jd}tj	j| j|jd}|r1d|f  S t j
|| jds?d|f  S d|j}t| | }|sV|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_value)service_being_enabledZincompatible_serviceFmsgrM   z"Disabling incompatible service: {}NrW   )r   r   r4   r   r   r   r[   rm   r1   Z!INCOMPATIBLE_SERVICE_STOPS_ENABLEprompt_for_confirmationrM   eventinfodisable)r!   Zcfg_block_disable_on_enabler   entuser_msge_msgZdisable_msgrd   r"   r"   r#   r\     s:   
z*UAEntitlement.handle_incompatible_servicesc              	   C   s$  ddl m} | jD ]}z||}W n tjy(   tjj|d}d|f Y   S w || jdd}|	 d t
jjk}|rtjj| j|jd}tjj| j|jd}tj|| jds^d|f  S td	|j |jdd
\}	}
|	sd}|
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.
        r   r   r   FT)rN   )r   r   r   zEnabling required service: {}rV   r9   
)rc   r   rW   )r   r   rI   r   r~   r   ZREQUIRED_SERVICE_NOT_FOUNDrm   r4   rj   r   rk   rl   ZREQUIRED_SERVICEr1   ZREQUIRED_SERVICE_STOPS_ENABLEr   r   rM   r   r   re   r]   r   ZERROR_ENABLING_REQUIRED_SERVICE)r!   r   r   r   r   r   Zis_service_disabledr   r   rd   rb   	error_msgr"   r"   r#   r_     sP   


z'UAEntitlement._enable_required_servicesc                 C   s  | j j| j}|stjtjfS | jD ]\}}}| |kr$tj	|f  S q|d di }t
 }|dg }|rQ|d |vrQtj	tjj| j|d d|dfS |dg }|rm|d |vrmtj	tjj| j|d d	fS |d
 }	|dg }
|d}tt|	}|
r|r|d|
vrtj	tjj| j|	d|
dfS |rtjj| j|	|d}z|d\}}t|}t|}W n ty   td| tj	|f Y S w |stj	|fS t|d}t|d}||k rtj	|fS ||kr||k rt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   r3   Zarchitecturesarchz, )r1   r   Zsupported_archesseriesversion)r1   r   kernelZkernelFlavorsZminKernelVersionZflavor)r1   r   Zsupported_kernels)r1   r   Z
min_kernel.z$Could not parse minKernelVersion: %smajorminorN)r4   r5   r6   r,   r   
APPLICABLEr   Z"NO_ENTITLEMENT_AFFORDANCES_CHECKEDrB   ry   r   Zget_platform_infoZINAPPLICABLE_ARCHrm   r1   joinZINAPPLICABLE_SERIESrematchRE_KERNEL_UNAMEgroupZINAPPLICABLE_KERNELZINAPPLICABLE_KERNEL_VERsplitint
ValueErrorrs   warning)r!   entitlement_cfgZerror_messageZfunctorZexpected_resultr3   platformZaffordance_archesZaffordance_seriesr   Zaffordance_kernelsZaffordance_min_kernelr   Zinvalid_msgZkernel_majorZkernel_minorZmin_kern_majorZmin_kern_minorr"   r"   r#   rx     s   






z"UAEntitlement.applicability_statusc                 C   r*   )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"   rf   r"   r"   r#   _perform_disablet  s   zUAEntitlement._perform_disablec              	   C   s:  ddl m} | jD ]}z||}W n  tjy1   tjj|d}tj	|j
tjd d|f Y   S w || j}| d tjjk}|rtjj|j| jd}tjj| j|jd}	tj|| jdsed|	f  S |srt	tjj|jd	 |jd
d\}
}|
sd}|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
        r   r   r   )Zinfo_msg	file_typeF)dependent_serviceservice_being_disabled)r   r   r   )r   TrV   r9   r   )rc   r   rW   )r   r   rK   r   r~   r   ZDEPENDENT_SERVICE_NOT_FOUNDrm   r   r   r   sysstderrr4   rj   r   rk   r   ZDEPENDENT_SERVICEr1   ZDEPENDENT_SERVICE_STOPS_DISABLEr   r   rM   ZDISABLING_DEPENDENT_SERVICEr   r]   Z"FAILED_DISABLING_DEPENDENT_SERVICE)r!   rT   r   r   r   r   r   Zis_service_enabledr   r   rd   rb   r   r"   r"   r#   _disable_dependent_services  sX   

z)UAEntitlement._disable_dependent_servicesc                 C   s   t  S )z%Check if system needs to be rebooted.)r   Zshould_rebootr+   r"   r"   r#   _check_for_reboot  s   zUAEntitlement._check_for_reboot	operationc                 C   s"   |   rttjj|d dS dS )zCheck if user should be alerted that a reboot must be performed.

        @param operation: The operation being executed.
        r   N)r   printr   ZENABLE_REBOOT_REQUIRED_TMPLrm   )r!   r   r"   r"   r#   _check_for_reboot_msg  s   z#UAEntitlement._check_for_reboot_msgc                 C   s   | j dg }t|sdS |  \}}|s8|du rdS |jtjkr4| j|d\}}|s3||_	d|fS nd|fS | j
|ds@dS | j dg }t|sNd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_disablerU   NrV   FZpost_disablezdisable operationr   rW   )rL   r6   r   rX   rq   rZ   r   ro   r   r]   r   r   )r!   rT   ra   rq   rb   rd   r   r"   r"   r#   r     s0   

zUAEntitlement.disablec                 C   s>   | j jstjS | j j| ji }|r|d drtjS tjS )z=Return whether the user is entitled to the entitlement or notr   entitled)r4   Zis_attachedr   rw   r5   r6   r,   rv   )r!   r   r"   r"   r#   ru     s   zUAEntitlement.contract_statusc                 C   sD   | j j| ji }|d}|sdS t|d}|t kr dS dS )z<Return entitlement access info as stale and needing refresh.ZexpiresFz%Y-%m-%dT%H:%M:%S.%fZT)r4   r5   r6   r,   r   strptimeZutcnow)r!   Zentitlement_contractZ
expire_strZexpiryr"   r"   r#   rr   
  s   
zUAEntitlement.is_access_expiredc                 C   st   | j d}|du rtjjS |dg }|D ]}|d| jkr5|d}|dkr/tjj  S tjj  S qtjjS )z6Check on the state of application on the status cache.status-cacheNr}   r,   r   enabled)r4   
read_cacher   rk   rl   r6   r,   r   )r!   status_cacheZservices_status_listr   Zservice_statusr"   r"   r#   "_check_application_status_on_cache  s   
z0UAEntitlement._check_application_status_on_cacheorig_accessdeltasallow_enablec                 C   s  |sdS | di }| di }| jd}t|tjk}|s9|r*t| |d }|r9d|v r9|d dtjfv }|rs|rD|rD|  }n|  \}}	|t	j
jkrg|  r`|   td| j ntd| j | jd	| j dS | d
}
|
s| d
}
| di }t| do|
}|rd| _|  \}}	|r|r|rtjj| jd}tj|tjd |   dS tjj| jd}tj|tjd dS dS )av  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: UserFacingError when auto-enable fails unexpectedly.
        Tr   Z
directivesr   r   Fz.Due to contract refresh, '%s' is now disabled.zgUnable to disable '%s' as recommended during contract refresh. Service is still active. See `ua status`zmachine-access-{}resourceTokenZobligationsZenableByDefault)r,   )r   )r6   r4   r   boolr   ZDROPPED_KEYZapply_series_overridesr   rj   r   rk   rl   rq   r   rs   r   r,   r   Zdelete_cache_keyrm   rN   rY   r   ZENABLE_BY_DEFAULT_TMPLr   r   r   re   ZENABLE_BY_DEFAULT_MANUAL_TMPL)r!   r   r   r   Zdelta_entitlementZdelta_directivesr   Ztransition_to_unentitledrj   rp   r   Zdelta_obligationsZenable_by_defaultrY   r   r"   r"   r#   process_contract_deltas*  sl   

	

z%UAEntitlement.process_contract_deltasc                 C   s   |   \}}|tjkrtj|fS | jj| j}|s%tj	t
jj| jdfS |d dddu r:tj	t
jj| jdfS |  \}}tjjtjtjjtji| }||fS )z4Return (user-facing status, details) for entitlementrh   r   r   F)rx   r   r   r   ry   r4   r5   r6   r,   ZUNAVAILABLEr   ZSERVICE_NOT_ENTITLEDrm   r1   rj   r   rk   r   ZACTIVErl   ZINACTIVE)r!   Zapplicabilityr|   r   rj   Zexplanationuser_facing_statusr"   r"   r#   r     s&   



z UAEntitlement.user_facing_statusc                 C   r*   )z
        The current status of application of this entitlement

        :return:
            A tuple of (ApplicationStatus, human-friendly reason)
        Nr"   r+   r"   r"   r#   rj     s   
z UAEntitlement.application_status)NFFr9   )F)Gr%   r&   r'   Zhelp_doc_urlrM   rR   r:   rE   rH   rJ   propertyabcabstractmethodstrr,   r   r0   r1   r2   r.   rA   r   r   rB   r   rF   rI   rK   r   rL   r   r
   rP   r   r$   rS   r	   r   re   r`   r   rq   rY   r   rn   r{   r   rz   r   r(   r\   r_   r   rx   r   r   r   r   r   r   ru   rr   r   rk   r   r   r   r   r   r   rj   r"   r"   r"   r#   r   3   s    			


1
B

5
:
W
D
,	


Y
r   )	metaclass),r   rs   r;   r   r   r   typingr   r   r   r   r   r   r	   r?   Zuaclientr
   r   r   r   r   r   r   Zuaclient.defaultsr   Zuaclient.statusr   r   r   r   r   r   r   Zuaclient.typesr   r   Zuaclient.utilr   r   Zget_event_loggerr   r   ABCMetar   r"   r"   r"   r#   <module>   s$    $$	$	
