
    g7                        d dl Z d dl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 d dlmZmZ d dlmZ d dlmZ ddgZd	d
dZ ej2                         Z e j6                   ej8                  e            Z G d de      Zd Z y)    N)AnyDictOptionalTuple)	apievent_logger
exceptionshttp	livepatchmessagessnapsystemutil)EntitlementWithMessageUAEntitlement)ApplicationStatus)StaticAffordanceg      ?g      ?z)Invalid Auth-Token provided to livepatch.z2Your running kernel is not supported by Livepatch.)zUnknown Auth-Tokenzunsupported kernelc            	           e Zd Zej                  j
                  ZdZej                  Z	ej                  Zej                  ZdZdZdZdZedeedf   fd       Zedeedf   fd       ZdefdZdefd	Zd
ej8                  defdZ	 	 dd
ej8                  dededefdZd
ej8                  fdZ dee!e"ejF                     f   fdZ$deee"ejF                     f   fdZ%d Z&	 dde'e(e)f   de'e(e)f   dedef fdZ* xZ+S )LivepatchEntitlementr   FTreturn.c                     ddl m} ddlm} t	        |t
        j                        t	        |t
        j                        fS )Nr   FIPSEntitlement)RealtimeKernelEntitlement)uaclient.entitlements.fipsr   uaclient.entitlements.realtimer   r   r   LIVEPATCH_INVALIDATES_FIPSREALTIME_LIVEPATCH_INCOMPATIBLE)selfr   r   s      A/usr/lib/python3/dist-packages/uaclient/entitlements/livepatch.pyincompatible_servicesz*LivepatchEntitlement.incompatible_services,   s=    >L #!D!D #)88	
 	
    c                    ddl m}  || j                        }t        |j	                         d   t
        j                  k(        t        j                  j                  | j                        d dft        j                  fddffS )Nr   r   )cfg)titlec                  \    t        j                         xs t        j                         dk(  S )Nwsl)r   is_containerget_virt_type r"   r    <lambda>z9LivepatchEntitlement.static_affordances.<locals>.<lambda>K   s(    ++- 3'')U2 r"   Fc                       S Nr*   )is_fips_enableds   r    r+   z9LivepatchEntitlement.static_affordances.<locals>.<lambda>Q   s     r"   )r   r   r$   boolapplication_statusr   ENABLEDr   "SERVICE_ERROR_INSTALL_ON_CONTAINERformatr%   !LIVEPATCH_ERROR_WHEN_FIPS_ENABLED)r   r   fips_entr.   s      @r    static_affordancesz'LivepatchEntitlement.static_affordances;   s     	?"txx0'')!,0A0I0II
 ;;BB** C 3 ::'
 	
r"   c                      y)N   r*   r   s    r    enable_stepsz!LivepatchEntitlement.enable_stepsV       r"   c                      y)N   r*   r9   s    r    disable_stepsz"LivepatchEntitlement.disable_stepsY   r;   r"   progressc                 L   |j                  t        j                         t        j                         sD|j                  dt        j                  j                  d             t        j                          t        j                         sF|j                  dt        j                  j                  d             	 t        j                  d       t        j                   |       	 t        j"                  d       t)        j*                  d| j,                  j.                  t(        j0                        }t)        j*                  d| j,                  j2                  t(        j4                        }t        j6                  ||t        j8                         t;        j<                         sF|j                  dt        j                  j                  d             	 t        j                  d       t;        jB                  ||       | jE                  |dd      S # t        j                  $ rR}t        j                  d|       |j                  dt        j                  j                  d             Y d	}~d	}~ww xY w# t        j                  $ rU}t        j                  d
|       t$        j'                  t        j                  j                  d             Y d	}~d	}~ww xY w# t        j                  $ r$}t        j>                  tA        |            d	}~ww xY w)zYEnable specific entitlement.

        @return: True on success, False otherwise.
        infosnapd)packagesz
snapd snapz!Failed to install snapd as a snapexc_infozsnap install snapdcommandNzFailed to refresh snapd snapzsnap refresh snapdr
   https)
http_proxyhttps_proxyretry_sleepszcanonical-livepatch snapzcanonical-livepatch	error_msgT)process_directivesprocess_token)#r?   r   INSTALLING_LIVEPATCHr   is_snapd_installedemitINSTALLING_PACKAGESr3   install_snapdis_snapd_installed_as_a_snapinstall_snapr	   ProcessExecutionErrorLOGwarningEXECUTING_COMMAND_FAILEDrun_snapd_wait_cmdrefresh_snapeventrA   r
   validate_proxyr$   rI   PROXY_VALIDATION_SNAP_HTTP_URLrJ   PROXY_VALIDATION_SNAP_HTTPS_URLconfigure_snap_proxySNAP_INSTALL_RETRIESr   is_livepatch_installedErrorInstallingLivepatchstrconfigure_livepatch_proxysetup_livepatch_config)r   r?   erI   rJ   s        r    _perform_enablez$LivepatchEntitlement._perform_enable\   s   
 	(778&&(MM44;;W;M  002MM,,33\3J	!!'* 	)	g& ((DHH'')L)L

 ))TXX))4+O+O
 	!!!#22	

 //1MM,,337 4 L!!"78 	++JD**T + 
 	
] 33 ?!L55<< 4 =   // 	KK6KCJJ11880 9  	8 33 L 99CFKKLsJ   =H (J K, I>,AI99I>K)A
K$$K),L#?LL#rN   rO   c           	      N   |j                  t        j                         | j                  j	                         j                  | j                        }|r	 t        |       |r|j                  d      }|s9t        j!                  d| j"                         | j                  j$                  d   }| j'                         \  }}|t(        j*                  k7  r[t        j-                  d	       |j                  dt        j.                         	 t1        j2                  t4        j6                  d
g       	 t1        j2                  t4        j6                  d|gd       yy# t        j                  $ rc}t        j                  t        |      |       |j                  dt        j                  j                  t        |                   Y d}~yd}~ww xY w# t        j                  $ r*}t        j                  t        |      |       Y d}~yd}~ww xY w# t        j                  $ r}}t        j8                  }	t:        j=                         D ]  \  }
}|
t        |      v s|	|z  }	 n |	t        j8                  k(  r|	t        |      z  }	|j                  d|	       Y d}~yd}~ww xY w)a  Processs configuration setup for livepatch directives.

        :param process_directives: Boolean set True when directives should be
            processsed.
        :param process_token: Boolean set True when token should be
            processsed.
        rD   rA   rL   NFresourceTokenzHNo specific resourceToken present. Using machine token as %s credentialsmachineTokenz&Disabling livepatch before re-enablingdisableenableTcapture)r?   r   SETTING_UP_LIVEPATCHmachine_token_fileentitlementsgetnameprocess_config_directivesr	   rW   rX   errorre   rR   LIVEPATCH_UNABLE_TO_CONFIGUREr3   debugr%   machine_tokenr0   r   DISABLEDrA   LIVEPATCH_DISABLE_REATTACHr   subpr   LIVEPATCH_CMDLIVEPATCH_UNABLE_TO_ENABLEERROR_MSG_MAPitems)r   r?   rN   rO   entitlement_cfgrh   livepatch_tokenr0   _detailsmsgerror_messageprint_messages               r    rg   z+LivepatchEntitlement.setup_livepatch_config   s7    	(77811>>@DDTYYO
)/: -11/BO"		&JJ
 #'"9"9"G"G"# ,0+B+B+D(!%6%?%??ABfh&I&IJ!KK!8!8) DE,,hH  Y 33 		#a&1	-::AA"%a& B  4 "77 !IIc!fqI1 ! 33 	994A4G4G4I 0M=$A.}, (===3q6MCfc*	sO   E %G 1(H G.AGGH' HHJ$'7J;JJ$c                     t        j                         syt         j                  dg}|j                  t        j
                  j                  dj                  |                   t        j                  |d       y)zYDisable specific entitlement

        @return: True on success, False otherwise.
        Trm    rF   ro   )
r   rc   r~   r?   r   EXECUTING_COMMANDr3   joinr   r}   )r   r?   cmds      r    _perform_disablez%LivepatchEntitlement._perform_disable   sc    
 //1&&	2&&--chhsm-D	
 	C&r"   c                    t         j                  d f}t        j                         s t         j                  t
        j                  fS 	 t        j                         }| t         j                  t
        j                  fS |S # t        j                  $ rD}t         j                  t
        j                  j                  |j                        fcY d }~S d }~ww xY w)N)livepatch_error)r   r1   r   rc   r{   r   LIVEPATCH_NOT_ENABLEDstatusr	   rW   WARNING LIVEPATCH_CLIENT_FAILURE_WARNINGr3   stderr+LIVEPATCH_APPLICATION_STATUS_CLIENT_FAILURE)r   r   livepatch_statusrh   s       r    r0   z'LivepatchEntitlement.application_status   s     $++T2//1%..0N0NOO	(//1 # "**DD   // 	!))99@@$%HH A  	s   B   C9CCCc                 *   t        j                         }|t         j                  j                  k(  rKt	        j
                         }dt        j                  j                  |j                  |j                        fS |t         j                  j                  k(  rKt	        j
                         }dt        j                  j                  |j                  |j                        fS |t         j                  j                  k(  rdt        j                  fS y)NT)versionarch)FN)r   on_supported_kernelLivepatchSupportUNSUPPORTEDr   get_kernel_infor   LIVEPATCH_KERNEL_NOT_SUPPORTEDr3   uname_releaseuname_machine_arch
KERNEL_EOLLIVEPATCH_KERNEL_EOLKERNEL_UPGRADE_REQUIRED!LIVEPATCH_KERNEL_UPGRADE_REQUIRED)r   supportkernel_infos      r    enabled_warning_statusz+LivepatchEntitlement.enabled_warning_status  s     //1i00<<< 002K77>>'55$77 ?   i00;;; 002K--44'55$77 5   i00HHH::  r"   c                     t        j                         t         j                  j                  k(  r$t	        j
                         st        j                  S y r-   )r   r   r   r   r   r(   r   *LIVEPATCH_KERNEL_NOT_SUPPORTED_DESCRIPTIONr9   s    r    status_description_overridez0LivepatchEntitlement.status_description_override+  s=    ))+))556'')FFFr"   orig_accessdeltasallow_enablec                    t         |   |||      ry|j                  di       }|j                  di       j                  dd      }|r(| j                  t	        j
                               \  }}|S | j                         \  }}|t        j                  k(  ry|j                  di       }	t        ddg      }
t        |
j                  |	            }t        |j                  d	d            }t        ||g      rxt        j                  d
       t        j                  t         j"                  j%                  | j&                               | j)                  t	        j
                         ||      S y)a1  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.
        TentitlementobligationsenableByDefaultF
directivescaCertsremoteServerrk   zANew livepatch directives or token. running setup_livepatch_config)service)r?   rN   rO   )superprocess_contract_deltasrt   rn   r   ProgressWrapperr0   r   r{   setr/   intersectionanyrX   rA   r]   r   #SERVICE_UPDATING_CHANGED_DIRECTIVESr3   ru   rg   )r   r   r   r   delta_entitlementprocess_enable_defaultenable_success_r0   delta_directivessupported_deltasrN   rO   	__class__s                r    r   z,LivepatchEntitlement.process_contract_deltas4  sm   $ 7*;M"JJ}b9!2!6!6}b!I!M!Mu"
 " $C,?,?,A BNA!! $ 7 7 9A!2!;!;;,00rB	>:;!))*:;
 VZZ?@"M23HH) JJ<<CC II D 
 ..,,.#5+ /  
 r"   )TT)F),__name__
__module____qualname__r   urlsLIVEPATCH_HOME_PAGEhelp_doc_urlru   LIVEPATCH_TITLEr%   LIVEPATCH_DESCRIPTIONdescriptionLIVEPATCH_HELP_TEXT	help_text#affordance_check_kernel_min_versionaffordance_check_kernel_flavoraffordance_check_seriesaffordance_check_archpropertyr   r   r!   r   r6   intr:   r>   r   r   r/   ri   rg   r   r   r   NamedMessager0   r   r   r   re   r   r   __classcell__)r   s   @r    r   r      s   ==44LD$$E00K,,I*/'%*"" !
u-CS-H'I 
 
 
E*:C*?$@ 
 
4c s D
(;(; D
 D
R $("	?%%? !? 	?
 
?B)<)< 	 (8+@+@"AA	B4	tXh3344	5@ #	6#s(^6 S#X6 	6
 
6 6r"   r   c                    | sy| j                  di       j                  di       }|j                  d      }|r7t        j                  t        j                  ddj                  |      gd       |j                  d	d
      }|j                  d      r|dd }|r8t        j                  t        j                  ddj                  |      gd       yy)a  Process livepatch configuration directives.

    We process caCerts before remoteServer because changing remote-server
    in the canonical-livepatch CLI performs a PUT against the new server name.
    If new caCerts were required for the new remoteServer, this
    canonical-livepatch client PUT could fail on unmatched old caCerts.

    @raises: ProcessExecutionError if unable to configure livepatch.
    Nr   r   r   configzca-certs={}Tro   r    /zremote-server={})rt   r   r}   r   r~   r3   endswith)r$   r   ca_certsremote_servers       r    rv   rv   m  s     +//bAJ~~i(H''$$X.
 	
 NN>26Mc"%cr*''"))-8
 	
 r"   )!loggingtypingr   r   r   r   uaclientr   r   r	   r
   r   r   r   r   r   uaclient.entitlements.baser   r   (uaclient.entitlements.entitlement_statusr   uaclient.typesr   LIVEPATCH_RETRIESr   get_event_loggerr]   	getLoggerreplace_top_level_logger_namer   rX   r   rv   r*   r"   r    <module>r      s     - -
 
 
 M F +#J  FN
 	&%%'g:::8DEL= L^
"
r"   