ÿØÿà JFIF      ÿÛ C      

!"$"$ÿÛ C  ÿÂ p " ÿÄ              ÿÄ             ÿÚ    ÕÔË®
(%	aA*‚XYD¡(J„¡E¢RE,P€XYae )(E¤²€B¤R¥	BQ¤¢ X«)X…€¤   @  

  ..............................................................................................................................................................................
.............................................................................                                                  
                                                                                                                                                                                     ÿØÿà JFIF      ÿÛ C      

!"$"$ÿÛ C  ÿÂ p " ÿÄ              ÿÄ             ÿÚ    ÕÔË®
(%	aA*‚XYD¡(J„¡E¢RE,P€XYae )(E¤²€B¤R¥	BQ¤¢ X«)X…€¤   @  

  ..............................................................................................................................................................................
.............................................................................                                                  
                                                                                                                                                                                     o
    Lb`                  
   @   s  d Z ddlZddlZddlZddlZddlZddlZddlZ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 ddl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$ ddl%m&Z&m'Z' dd	l(m)Z) dd
l(m*Z* ddl+m,Z,m-Z- ddl.m/Z/m0Z0m1Z1m2Z2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z: ddl;m<Z<m=Z= dZ>dZ?dZ@dZAdZBg dZCdZDdZEeF ZGG dd dejHZIdddZJdd ZKdd ZLdd d!ZMd"d# ZNd$d% ZOd&d' ZPd(d) ZQd*d+ ZRd,d- ZSd.d/ ZTd0d1 ZUd2d3 ZVd4d5 ZWd6d7 ZXd8d9 ZYd:d; ZZd<d= Z[d>ej\fd?d@Z]d>ej\fdAdBZ^d>ej\fdCdDZ_dEdF Z`dGdHdIdJZadKeeb d>ej\fdLdMZcdNdO ZddPdQ ZeeKdRdS ZfeKdTdU ZgdVdW ZheLeKeMeheJdXdYdZ Zid>ej\d[ejd\ejkfd]d^ZleLeKeMeheJd_d`da ZmeLeKeM eJdbd\enfdcddZod>ej\deejd\enfdfdgZpd>ej\d\dfdhdiZqeKeJdjdkdl ZreNeKeJdmdndo Zs	ddpebdqeen d\dfdrdsZteKd>ej\fdtduZud>ej\fdvdwZvdxdy Zwddzd{Zxdd|d}Zyd>ej\fd~dZzeM d>ej\fddZ{d>ej\fddZ|eKeJdd>ej\fddZ}d>ej\de&debdebd\df
ddZ~dd ZdddZdd Zdd ZedddZedkr\ee  dS dS )z8Client to manage Ubuntu Advantage services on a machine.    Nwraps)DictListOptionalTuple)actionsconfigcontractdaemonentitlementsevent_logger
exceptionslockmessagessecuritysecurity_status)status)utilversion)AptProxyScopesetup_apt_proxy)AutoAttachCloudInstance)identity)AttachActionsConfigFileIncorrectTypeError)CLOUD_BUILD_INFOCONFIG_FIELD_ENVVAR_ALLOWLISTDEFAULT_CONFIG_FILEDEFAULT_LOG_FORMATPRINT_WRAP_WIDTH)ApplicationStatusCanDisableFailureCanEnableFailureCanEnableFailureReason)LIVEPATCH_CMD)refresh_motdupdate_apt_and_motd_messagesZuaz{name} {command} [flags]zAUse {name} {command} --help for more information about a command.z}Account: {account}
Subscription: {subscription}
Valid until: {contract_expiry}
Technical support level: {tech_support_level}
z$https://auth.contracts.canonical.com)Ztabularjsonyamlzua_logs.tar.gz)zua-timer.servicezua-timer.timerzua-auto-attach.pathzua-auto-attach.servicezua-reboot-cmds.servicezubuntu-advantage.servicec                       sh   e Zd Zdddejdfdef fddZdd Zd fdd		Ze	d
e
ee ee f fddZ  ZS )UAArgumentParserN	base_descc                    s   t  j||||d || _d S )N)progusageepilogformatter_class)super__init__r+   )selfr,   r-   r.   r/   r+   	__class__ ./usr/lib/python3/dist-packages/uaclient/cli.pyr1   `   s   
zUAArgumentParser.__init__c                 C   s    |  tj | d|d  d S )N   
)print_usagesysstderrexit)r2   messager5   r5   r6   errorq   s   zUAArgumentParser.errorFc                    sP   | j rt \}}t|}|rt|| }d| j g| | _t j|d d S )Nr8   file)r+   r*   _get_service_descriptionssortedjoindescriptionr0   
print_help)r2   r@   show_allnon_beta_services_descbeta_services_descZservice_descriptionsr3   r5   r6   rE   u   s   
zUAArgumentParser.print_helpreturnc            
   	   C   s   t  } d}g }g }tt  }|D ]K}ztj| |d d}W n
 tjy*   Y qw |d|d }|j	r=d
|j	}nd}tj|j
||j|dtdd	d	d
}	|jrY||	 q||	 q||fS )Nz - {name}: {description}{url}namecfgrJ   ZpresentedAsz ({}) )rJ   rD   urlz   F)widthsubsequent_indentbreak_long_wordsbreak_on_hyphens)r	   UAConfigr
   Zget_available_resourcesr   entitlement_factoryr   ZEntitlementNotFoundErrorgetZhelp_doc_urlformattextwrapfillrD   r    Zis_betaappend)
rL   Zservice_info_tmplrG   rH   Z	resourcesZresourceent_clsZpresentation_namerN   Zservice_infor5   r5   r6   rA      s@   
z*UAArgumentParser._get_service_descriptions)NF)__name__
__module____qualname__argparseHelpFormatterstrr1   r>   rE   staticmethodr   r   rA   __classcell__r5   r5   r3   r6   r*   _   s    (r*   c                        fdd}|S )z1Decorator asserting exclusive access to lock filec                       t   fdd}|S )Nc                    sF   t j| d  |d| i|}W d    |S 1 sw   Y  |S )N)rL   lock_holderrL   )r   ZSingleAttemptLock)rL   argskwargsZretval)fre   r5   r6   new_f   s   
z0assert_lock_file.<locals>.wrapper.<locals>.new_fr   rh   ri   re   rh   r6   wrapper   s   z!assert_lock_file.<locals>.wrapperr5   )re   rm   r5   rk   r6   assert_lock_file   s   	rn   c                       t   fdd}|S )zDecorator asserting root userc                     s"   t  dkr
t  | i |S )Nr   )osgetuidr   ZNonRootUserError)rf   rg   rl   r5   r6   ri      s   zassert_root.<locals>.new_fr   rj   r5   rl   r6   assert_root   s   rr   c                    ro   )z>Decorator to verify if correct params are used for json formatc                    sX   | s | g|R i |S | j dkr!| js!tj}tj|j|jd | g|R i |S )Nr(   msgmsg_code)rV   
assume_yesr   ZJSON_FORMAT_REQUIRE_ASSUME_YESr   UserFacingErrorrt   rJ   )cmd_argsrf   rg   rt   rl   r5   r6   ri      s   z&verify_json_format_args.<locals>.new_fr   rj   r5   rl   r6   verify_json_format_args   s   
ry   c                    rc   )zDecorator asserting attached config.
    :param msg_function: Optional function to generate a custom message
    if raising an UnattachedError
    c                    rd   )Nc                    s^   |j s%rt| dd}t| dd}|||d}t|}|t }| | fd|i|S )NcommandrM   service)rz   service_namesrL   rL   )is_attachedgetattrr   ZUnattachedError)rf   rL   rg   rz   r|   rt   	exception)rh   msg_functionr5   r6   ri      s   
z/assert_attached.<locals>.wrapper.<locals>.new_fr   rj   r   rl   r6   rm      s   z assert_attached.<locals>.wrapperr5   )r   rm   r5   r   r6   assert_attached   s   r   c                    ro   )z&Decorator asserting unattached config.c                    s   |j rt| | |dS )NrL   )r}   r   AlreadyAttachedErrorrf   rL   rl   r5   r6   ri      s   
z"assert_not_attached.<locals>.new_fr   rj   r5   rl   r6   assert_not_attached   s   r   c                 C   s*   d| _ d| _tjt| j d| _d| j_| S )z9Build or extend an arg parser for auto-attach subcommand.auto-attachzDAutomatically attach an Ubuntu Advantage token on Ubuntu Pro images.rJ   rz   Flags)r,   rD   
USAGE_TMPLrV   NAMEr-   
_optionalstitleparserr5   r5   r6   auto_attach_parser  s   r   c                 C   s2   d| _ d| _tjt| j d| _| jdddd | S )z<Build or extend an arg parser for 'collect-logs' subcommand.collect-logsz?Collect UA logs and relevant system information into a tarball.r   z-oz--outputzEtarball where the logs will be stored. (Defaults to ./ua_logs.tar.gz)help)r,   rD   r   rV   r   r-   add_argumentr   r5   r5   r6   collect_logs_parser  s   r   c                 C   s0   t jtdd| _d| _d| _| jdddd | S )	z;Build or extend an arg parser for 'config show' subcommand.z
show [key]r   showz(Show customisable configuration settingskey?z6Optional key or key(s) to show configuration settings.nargsr   )r   rV   r   r-   r,   rD   r   r   r5   r5   r6   config_show_parser   s   r   c                 C   sD   t jtdd| _d| _d| _d| j_| jddd	t
jd	 | S )
z:Build or extend an arg parser for 'config set' subcommand.zset <key>=<value>r   setz5Set and apply Ubuntu Advantage configuration settingsr   key_value_pairzQkey=value pair to configure for Ubuntu Advantage services. Key must be one of: {}, r   )r   rV   r   r-   r,   rD   r   r   r   rC   r	   UA_CONFIGURABLE_KEYSr   r5   r5   r6   config_set_parser-  s   
	r   c                 C   sF   t jtdd| _d| _d| _| jdddtj	dd d	| j
_| S )
z<Build or extend an arg parser for 'config unset' subcommand.zunset <key>r   unsetz,Unset Ubuntu Advantage configuration settingr   zEconfiguration key to unset from Ubuntu Advantage services. One of: {}r   )r   metavarr   )r   rV   r   r-   r,   rD   r   rC   r	   r   r   r   r   r5   r5   r6   config_unset_parserA  s   r   c                 C   s   t jtdd| _d| _d| _d| j_| jdddd	}|j	d
dd}|j
td t| |j	ddd}|j
td t| |j	ddd}|j
td t| | S )z4Build or extend an arg parser for config subcommand.zconfig <command>r   r	   z%Manage Ubuntu Advantage configurationr   Available Commandsrz   rM   r   destr   r   z2show all Ubuntu Advantage configuration setting(s)r   actionr   z*set Ubuntu Advantage configuration settingr   z,unset Ubuntu Advantage configuration setting)r   rV   r   r-   r,   rD   r   r   add_subparsers
add_parserset_defaultsaction_config_showr   action_config_setr   action_config_unsetr   )r   
subparsersZparser_showZ
parser_setZparser_unsetr5   r5   r6   config_parserR  s.   r   c                 C   s~   t jtdd| _d| _d| _d| j_| jdddt	d	 | jd
dddd | jdt
ddd | jddddgddd | S )z4Build or extend an arg parser for attach subcommand.zattach <token>r   attachz_Attach this machine to Ubuntu Advantage with a token obtained from https://ubuntu.com/advantager   tokenr   z6token obtained for Ubuntu Advantage authentication: {}r   z--no-auto-enablestore_falseauto_enablez4do not enable any recommended services automatically)r   r   r   z--attach-configrzKuse the provided attach config file instead of passing the token on the cli)typer   --formatstoreclir(   4output enable in the specified format (default: cli)r   choicesdefaultr   )r   rV   r   r-   r,   rD   r   r   r   UA_AUTH_TOKEN_URLr^   FileTyper   r5   r5   r6   attach_parsero  s>   r   c                 C   s6   t jtdd| _d| _d| _d| j_| jddd | S )	z1Build or extend an arg parser for fix subcommand.z"fix <CVE-yyyy-nnnn+>|<USN-nnnn-d+>r   fixzLInspect and resolve CVEs and USNs (Ubuntu Security Notices) on this machine.r   security_issuezwSecurity vulnerability ID to inspect and resolve on this system. Format: CVE-yyyy-nnnn, CVE-yyyy-nnnnnnn or USN-nnnn-ddr   	r   rV   r   r-   r,   rD   r   r   r   r   r5   r5   r6   
fix_parser  s   r   c                 C   s0   d| _ tj| _td| _| jddddd | S )z=Build or extend an arg parser for security-status subcommand.security-statusa          Show security updates for packages in the system, including all
        available ESM related content.

        Besides the list of security updates, it also shows a summary of the
        installed packages based on the origin.
        - main/restricted/universe/multiverse: packages from the Ubuntu archive
        - ESM Infra/Apps: packages from ESM
        - third-party: packages installed from non-Ubuntu sources
        - unknown: packages which don't have an installation source (like local
          deb packages or packages for which the source was removed)

        The summary contains basic information about UA and ESM. For a complete
        status on UA services, run 'ua status'
        r   z$Format for the output (json or yaml))r(   r)   T)r   r   required)r,   r^   RawDescriptionHelpFormatterr/   rW   dedentrD   r   r   r5   r5   r6   security_status_parser  s   r   c                 C   s@   d| _ d| _tjtdd| _d| j_| jdg ddd	d
d | S )z5Build or extend an arg parser for refresh subcommand.refreshz?Refresh existing Ubuntu Advantage contract and update services.zrefresh [contract|config]r   r   target)r
   r	   r   r   Na  Target to refresh. `ua refresh contract` will update contract details from the server and perform any updates necessary. `ua refresh config` will reload /etc/ubuntu-advantage/uaclient.conf and perform any changes necessary. `ua refresh messages` will refresh the APT and MOTD messages associated with UA. `ua refresh` is the equivalent of `ua refresh config && ua refresh contract && ua refresh motd`.)r   r   r   r   )	r,   rD   r   rV   r   r-   r   r   r   r   r5   r5   r6   refresh_parser  s   r   c                K   s>   | j dkrttt| dS ttjt|dd dS )Nr(   F)Zdefault_flow_styler   )rV   printr(   dumpsr   r)   Z	safe_dump)rf   rL   rg   r5   r5   r6   action_security_status  s   

r   c                K   s:   t tj| jsd| j}t|t|| j}|j	S )NzWError: issue "{}" is not recognized.
Usage: "ua fix CVE-yyyy-nnnn" or "ua fix USN-nnnn")
rematchr   ZCVE_OR_USN_REGEXr   rV   r   rw   Zfix_security_issue_idvalue)rf   rL   rg   rt   Z
fix_statusr5   r5   r6   
action_fix  s   
r   c                 C   sT   t jtdd}|| _d| _d| _d| j_| jdddd | jd	d
ddgddd | S )z4Build or extend an arg parser for detach subcommand.detachr   z3Detach this machine from Ubuntu Advantage services.r   --assume-yes
store_truez;do not prompt for confirmation before performing the detachr   r   r   r   r   r(   r   r   r   r   r-   r5   r5   r6   detach_parser  s$   r   rL   c                 C   s   t jtdd}|| _d| _d| _d| j_| jdddd	d
	t
j|dd | jddttd dtd d | jdddd | S )z2Build or extend an arg parser for help subcommand.zhelp [service]r   r   z=Provide detailed information about Ubuntu Advantage services.	Argumentsr{   r   r   z-a service to view help output for. One of: {}r   r   r   r   r   r   r   z1output help in the specified format (default: {})r   --allr   (Allow the visualization of beta servicesr   )r   rV   r   r-   r,   rD   _positionalsr   r   rC   r   valid_servicesSTATUS_FORMATSr   rL   r-   r5   r5   r6   help_parser  s:   	r   c                 C   s   t jtdd}d| _|| _d| _d| j_d| j_| j	ddd	d
d
tj|dd | j	dddd | j	dddd | j	ddddgddd | S )z4Build or extend an arg parser for enable subcommand.zenable <service> [<service>]r   z#Enable an Ubuntu Advantage service.enabler   r   r{   r   +zBthe name(s) of the Ubuntu Advantage services to enable. One of: {}r   r   r   r   r   z;do not prompt for confirmation before performing the enabler   z--betaz allow beta service to be enabledr   r   r(   r   r   r   rV   r   rD   r-   r,   r   r   r   r   rC   r   r   r   r5   r5   r6   enable_parser>  sB   r   c                 C   s   t jtdd}d| _|| _d| _d| j_d| j_| j	ddd	d
d
tj|dd | j	dddd | j	ddddgddd | S )z5Build or extend an arg parser for disable subcommand.zdisable <service> [<service>]r   z$Disable an Ubuntu Advantage service.disabler   r   r{   r   r   zBthe name(s) of the Ubuntu Advantage services to disable One of: {}r   r   r   r   r   z<do not prompt for confirmation before performing the disabler   r   r   r(   z5output disable in the specified format (default: cli)r   r   r   r5   r5   r6   disable_parsere  s<   r   c              	   C   s   t jtdd}|| _d| _d| _tj| _t	
d| _| jddddd	 | jd
dttd dtd d | jddddd | jdddd d| j_| S )z4Build or extend an arg parser for status subcommand.r   r   z<Output the status information for Ubuntu Advantage services.uA          Report current status of Ubuntu Advantage services on system.

        This shows whether this machine is attached to an Ubuntu Advantage
        support contract. When attached, the report includes the specific
        support contract details including contract name, expiry dates, and the
        status of each service on this system.

        The attached status output has four columns:

        * SERVICE: name of the service
        * ENTITLED: whether the contract to which this machine is attached
          entitles use of this service. Possible values are: yes or no
        * STATUS: whether the service is enabled on this machine. Possible
          values are: enabled, disabled, n/a (if your contract entitles
          you to the service, but it isn't available for this machine) or — (if
          you aren't entitled to this service)
        * DESCRIPTION: a brief description of the service

        The unattached status output instead has three columns. SERVICE
        and DESCRIPTION are the same as above, and there is the addition
        of:

        * AVAILABLE: whether this service would be available if this machine
          were attached. The possible values are yes or no.

        If --simulate-with-token is used, then the output has five
        columns. SERVICE, AVAILABLE, ENTITLED and DESCRIPTION are the same
        as mentioned above, and AUTO_ENABLED shows whether the service is set
        to be enabled when that token is attached.

        If the --all flag is set, beta and unavailable services are also
        listed in the output.
        z--waitr   FzBlock waiting on ua to complete)r   r   r   r   r   r   z3output status in the specified format (default: {})r   z--simulate-with-tokenZTOKENz1simulate the output status using a provided token)r   r   r   r   r   r   r   )r   rV   r   r-   rD   r,   r^   r   r/   rW   r   r   r   r   r   r   r5   r5   r6   status_parser  sJ   %r   T)update_statusc                C   s   |   \}}|s1t| j |dur0t|tr0|jdur0t|jj tj	|jj|jj| jd nt
| j |r?tj|d |S )a=  Perform the disable action on a named entitlement.

    :param entitlement_name: the name of the entitlement to enable
    :param cfg: the UAConfig to pass to the entitlement
    :param assume_yes:
        Assume a yes response for any prompts during service enable

    @return: True on success, False otherwise
    N	error_msg
error_coder{   r   )r   eventservice_failedrJ   
isinstancer"   r=   infort   r>   service_processed	ua_statusr   )entitlementrL   rv   r   retreasonr5   r5   r6   _perform_disable  s    

r   namesc                 C   sH   g }| D ]}|t j|dddv r|| qtt| t| }||fS )zReturn a list of valid entitlement names.

    :param names: List of entitlements to validate
    :return: a tuple of List containing the valid and invalid entitlements
    T)rL   
allow_betaZ	all_names)r   r   rY   rB   r   )r   rL   entitlements_foundent_nameentitlements_not_foundr5   r5   r6   get_valid_entitlement_names  s   
r   c                K   sh   t |d}| d jd }| d j }| j|vr2| d jd   tdd	|dS )zGPerform the config action.

    :return: 0 on success, 1 otherwise
    r   r   r	   z
<command> must be one of: {}r   N)

get_parser_get_positional_actionsr   keysrz   rE   r   rw   rV   rC   )rf   rL   rg   r   	subparserZvalid_choicesr5   r5   r6   action_config  s   

r  c                K   s   | j r9| j tjvr(d| j dtj}|dd }ttj	|t
d| dtdj| j t|| j dd	 d
S ttdd tjD d }d| d }tjD ]}t|j|t||dd	 qP|jsf|jrr|jsl|jrttd dS dS dS )zPerform the 'config show' action optionally limit output to a single key

    :return: 0 on success
    :raise UserFacingError: on invalid keys
    z
'{}' must be one of: {}r   :r7    )rO   rP   z{key} {value}N)r   r   r   c                 S   s   g | ]}t |qS r5   )len).0xr5   r5   r6   
<listcomp>4  s    z&action_config_show.<locals>.<listcomp>   z{key: <z	} {value}zn
Error: Setting global apt proxy and ua scoped apt proxy at the same time is unsupported. No apt proxy is set.)r   r	   r   rV   rC   findr   rw   rW   rX   r    r   r~   r`   maxglobal_apt_http_proxyglobal_apt_https_proxyua_apt_http_proxyua_apt_https_proxy)rf   rL   rg   rt   Zindent_positionZ	col_widthZrow_tmplr   r5   r5   r6   r     s@   
r   c             	   K   s  ddl m} ddlm} t|d}| d jd }| d jd }z
| jd\}}	W n t	yA   |
  td| jw |tjvrW|
  td	d
tj|dv r|dd }
|
dkrjtj}ntj}t|
|	| ||	i}|di | tj|}| \}}|tjkr|di | n||jv r|dd }
|
dkrtj}ntj}t|
|	| t|jp|j }|rt!t"j#jddd t$|t%j&||	 d|_d|_ n||j'|j( v r4d|v rdnd}
|
dkrtj}ntj}||j'v rt!t"j)j|
d d| }t|
|	| t|j*p|j+}|r%t!t"j#jddd t$|t%j,||	 d|_*d|_+n1|dv rezt-|	}	|	dk rJt	d|W n t	yd   |
  t!d td||	w t.|||	 dS )zMPerform the 'config set' action.

    @return: 0 on success, 1 otherwise
    r   )configure_livepatch_proxy)configure_snap_proxyr   r	   r   =z%
Expected <key>=<value> but found: {}
<key> must be one of: {}r   
http_proxyhttps_proxy_httpr7   zua scoped aptz
global apt)Zcurrent_proxyZprevious_proxyNhttpsprotocol_typeglobal_)Zupdate_messaging_timerZupdate_status_timerZmetering_timerzInvalid interval for {}rM   zECannot set {} to {}: <value> for interval must be a positive integer.r5   )/uaclient.entitlements.livepatchr  uaclient.snapr  r   r   r   r   split
ValueErrorrE   r   rw   rV   r	   r   rC   r   ZPROXY_VALIDATION_SNAP_HTTP_URLZPROXY_VALIDATION_SNAP_HTTPS_URLZvalidate_proxyr   	livepatchLivepatchEntitlementapplication_statusr!   ENABLEDua_scoped_proxy_optionsZPROXY_VALIDATION_APT_HTTP_URLZPROXY_VALIDATION_APT_HTTPS_URLboolr  r  r   r   ZWARNING_APT_PROXY_OVERWRITEconfigure_apt_proxyr   UACLIENT&deprecated_global_scoped_proxy_optionsglobal_scoped_proxy_optionsWARNING_APT_PROXY_SETUPr  r  GLOBALintsetattr)rf   rL   rg   r  r  r   r   r  set_key	set_valuer  Zvalidate_urlr   livepatch_statusr  Zunset_currentr5   r5   r6   r   C  s   








r   c                K   sd  ddl m} ddlm} ddlm} | jtjvr?t	|d}|
 d jd }|
 d jd }|  tdd	tj| jd
v rh| jdd }	||	d tj|}
|
 \}}|tjkrg||	d nA| j|jv rxt||j| jd n1| j|j|j v r| j|jv rd| jv rdnd}	ttj j|	d d| j | _t||j!| jd t"|| jd dS )zOPerform the 'config unset' action.

    @return: 0 on success, 1 otherwise
    r   )r   )unconfigure_livepatch_proxy)unconfigure_snap_proxyr   r	   r   r  r   r  r  r  Nr  r  r  )#uaclient.aptr   r  r2  r  r3  r   r	   r   r   r   r   rE   r   rw   rV   rC   r  r   r!  r"  r#  r!   r$  r%  r'  r(  r)  r*  r   r   r   r+  r,  r.  )rf   rL   rg   r   r2  r3  r   r   r  r  r   r1  r  r5   r5   r6   r     sN   





r   c                 C   sx   t ||d\}}|r |r tj}|jd|| d|dd}|S |r.tjjd|d}|S tjj| d|dd}|S )zGenerates a custom message for enable/disable commands when unattached.

    Takes into consideration if the services exist or not, and notify the user
    accordingly.)r   rL   r   rM   )valid_service	operationinvalid_serviceservice_msg)r5  z See https://ubuntu.com/advantager6  r7  r8  )r   r   Z!MIXED_SERVICES_FAILURE_UNATTACHEDrV   rC   Z VALID_SERVICE_FAILURE_UNATTACHEDINVALID_SERVICE_OP_FAILURE)rz   r|   rL   r   r   rt   r5   r5   r6   %_create_enable_disable_unattached_msg  s.   
	r;  z
ua disablec                K   s   t | dg }t||\}}d}|D ]}tj||d}||| jd}	|t|	|| jdM }q|rSddtj|dd d }
d	tj	|
d
ddd}t
jdd||dt  |r[dS dS )zbPerform the disable action on a list of entitlements.

    @return: 0 on success, 1 otherwise
    r{   TrK   rv   Try r   rL   r   .r8   P   FrO   rQ   rR   r   r9  r   r	  )r~   r   r   rT   rv   r   rC   r   rW   wrapr   ZInvalidServiceToDisableErrorr   process_events)rf   rL   rg   r   r   r   r   r   rZ   entvalid_namesr8  r5   r5   r6   action_disable  s>   	rF  r   rI   c                C   sP   t j||d}d|}dtjd| d dddd}tjjd	d| |d
S )z{
    Constructs the MESSAGE_INVALID_SERVICE_OP_FAILURE message
    based on the attempted services and valid services.
    r>  r   r8   r=  r?  r@  FrA  r   r9  )r   r   rC   rW   rB  r   r:  rV   )r   rL   r   Zvalid_services_namesrE  r8  r5   r5   r6   -_create_enable_entitlements_not_found_message5  s"   

	rG  z	ua enablec                K   s  t tj zt| W n tjtjfy)   t	j
tjdd t jtjd Y nw t| dg }t||\}}d}|D ]}z]tj||| j| jd\}}	tj|d |s|	durt|	tr|	jdurtt |	jj t j|	jj|	jj|d |	jtjkr|| n|rt j|d	 n|s|	du rt j |d	 ||M }W q; tjy }
 zt |
j t j|
j|
j!|d d
}W Y d}
~
q;d}
~
ww |rt"||| jd}t #| tj|j|jdt $  |rdS dS )z^Perform the enable action on a named entitlement.

    @return: 0 on success, 1 otherwise
    T)exc_info)Zwarning_msgr{   rv   r   r   Nr   )r{   Fr>  rs   r   r	  )%r   r   r   ZREFRESH_CONTRACT_ENABLEr
   request_updated_contractr   UrlErrorrw   loggingdebugREFRESH_CONTRACT_FAILUREwarningr~   r   r   enable_entitlement_by_namerv   Zbetar   r   r   r#   r=   rt   r>   rJ   r   r$   ZIS_BETArY   r   r   ru   rG  Zservices_failedrC  )rf   rL   rg   r   r   r   r   r   ent_retr   ert   r5   r5   r6   action_enableP  sn   	




rS  z	ua detachc                C   s   t || jdS )zXPerform the detach action for this machine.

    @return: 0 on success, 1 otherwise
    r<  )_detachrv   r   r5   r5   r6   action_detach  s   	rU  rv   c                 C   s   g }t jD ]}|| |d}|jdd\}}|r|| q	 |jdd d |rHt|dkr0dnd	}td
| |D ]}td|j	 q<t
j|dsPdS |D ]
}t|| |dd qR|   t  t|  ttj t  dS )a=  Detach the machine from the active Ubuntu Advantage subscription,

    :param cfg: a ``config.UAConfig`` instance
    :param assume_yes: Assume a yes answer to any prompts requested.
         In this case, it means automatically disable any service during
         detach.

    @return: 0 on success, 1 otherwise
    )rL   rv   T)Zignore_dependent_servicesc                 S   s
   t | jS N)r  Zdependent_services)rD  r5   r5   r6   <lambda>  s   
 z_detach.<locals>.<lambda>)r   r	  srM   z,Detach will disable the following service{}:z    {}r<  F)rv   r   r   )r   ENTITLEMENT_CLASSESZcan_disablerY   sortr  r   r   rV   rJ   r   Zprompt_for_confirmationr   Zdelete_cacher   startr'   r   ZDETACH_SUCCESSrC  )rL   rv   Z
to_disablerZ   rD  r   r  suffixr5   r5   r6   rT    s4   


rT  c                 C   s   d }| j r| j di di d}|r ttjj|d nttj t	  t
| \}}t|}tt| t  d S )NZmachineTokenInfoZcontractInforJ   )contract_name)Zmachine_tokenrU   r   r   r   ZATTACH_SUCCESS_TMPLrV   ZATTACH_SUCCESS_NO_CONTRACT_NAMEr   stopr   r   r   format_tabularr   handle_unicode_charactersrC  )rL   r]  r   Z_retoutputr5   r5   r6   _post_cli_attach  s    
rb  zua auto-attachc             
   C   s  t j|jdd}|rd}t| t| dS d }zt }W nD tj	yc } z7|j
r0t|t|tjr<ttjt|tjrHttjt|tjrYttjj|jdttjd }~ww |slttjt }|j
r|d}t|t|krtt|td t|dd	dkrttjzt|| W n tj y   t!"tj# Y d
S  tjy   Y d
S w t$| dS )Nzfeatures.disable_auto_attach)r	   Zpath_to_valuez8Skipping auto-attach. Config disable_auto_attach is set.r   )
cloud_typezinstance-idz:Re-attaching Ubuntu Advantage subscription on new instanceTr<  r	  )%r   Zis_config_value_truerL   rL  rM  r   r   Zcloud_instance_factoryr   ZCloudFactoryErrorr}   r   r   ZCloudFactoryNoCloudErrorrw   r   ZUNABLE_TO_DETERMINE_CLOUD_TYPEZCloudFactoryNonViableCloudErrorZUNSUPPORTED_AUTO_ATTACHZ!CloudFactoryUnsupportedCloudErrorZNonAutoAttachImageErrorZ"UNSUPPORTED_AUTO_ATTACH_CLOUD_TYPErV   rc  Zget_instance_idZ
read_cacher`   ZAlreadyAttachedOnPROErrorrT  ZDETACH_AUTOMATION_FAILUREr   Zauto_attachrK  r   r   ZATTACH_FAILURErb  )rf   rL   Zdisable_auto_attachrt   instancerR  Zcurrent_iidZprev_iidr5   r5   r6   action_auto_attach  sn   


re  z	ua attachc             
   C   s  | j s| jstjtjjtjjd| j r"| jr"tjtjjtjjd| j r+| j }d }n(zt	
t| j}W n tyL } z
tj| jj|jdd }~ww |j }|j}| joY|d u }z
tj|||d W n tjyp   t w d}|d ur| jrt||\}}	|D ]9}
tj||
ddd\}}|sd}|d urt|tjr|jd urt|jj tj|jj|jj|
d qt|
 q|	rt|	|dd	}tj|jt j!d
 tj|j|jd d}t"| |S )Nrs   )Zconfig_namer>   )r   allow_enabler   TrI  r	  r   r>  )	file_typer   r   )#r   attach_configr   rw   r   ZATTACH_REQUIRES_TOKENrt   rJ   ZATTACH_TOKEN_ARG_XOR_CONFIGr   Z	from_dictr)   Z	safe_loadr   ZAttachInvalidConfigFileErrorZenable_servicesr   r   Zattach_with_tokenrK  ZAttachErrorr   rP  r   r   r#   r=   r   r   r>   r   rG  r:   r;   rb  )rf   rL   r   Zenable_services_overrideri  rR  rf  r   foundZ	not_foundrJ   rQ  r   rt   r5   r5   r6   action_attach4  s   



rk  filenamereturn_codesc              
   C   sj   zt j|  |d\}}W n tjy, } zt d|t| W Y d}~dS d}~ww t || dS )zCHelper which runs a command and writes output or error to filename.)Zrcsz{}-errorN)r   Zsubpr  r   ZProcessExecutionError
write_filerV   r`   )cmdrl  rm  outr  rR  r5   r5   r6   _write_command_output_to_file~  s   $rq  c          	   	   C   s  | j pt}t }tdd| tdd| tdtd| tdd| td	d
dd tD d| tD ]}td|d||ddgd qB|j	pYt
|j|j|j|dtgdd tjD R }|D ]}tj|rt|}t|}t|| t|| qqt|d}|j|dd W d    n1 sw   Y  W d    d S W d    d S 1 sw   Y  d S )Nzcloud-idz{}/cloud-id.txtzua status --format jsonz{}/ua-status.jsonz	{} statusz{}/livepatch-status.txtzsystemctl list-timers --allz{}/systemd-timers.txtzxjournalctl --boot=0 -o short-precise {} -u cloud-init-local.service -u cloud-init-config.service -u cloud-config.servicer  c                 S   s   g | ]}d |v rd |qS )z.servicez-u {})rV   )r  rX  r5   r5   r6   r    s    z'action_collect_logs.<locals>.<listcomp>z{}/journalctl.txtzsystemctl status {}z	{}/{}.txtr      )rm  zjobs-statusc                 s   s.    | ]}t |tjjr|jj|jd V  qdS ))rJ   N)
issubclassr   ZrepoZRepoEntitlementZrepo_list_file_tmplrV   rJ   )r  r   r5   r5   r6   	<genexpr>  s    
z&action_collect_logs.<locals>.<genexpr>zw:gzzlogs/)Zarcname)ra  UA_COLLECT_LOGS_FILEtempfileZTemporaryDirectoryrq  rV   r%   rC   UA_SERVICESZcfg_pathr   log_fileZtimer_log_fileZdaemon_log_fileZ	data_pathr   r   rY  rp   pathisfiler   Z	load_fileredact_sensitive_logsrn  shutilcopytarfileopenadd)	rf   rL   Zoutput_fileZ
output_dirr{   Zua_logslogZlog_contentresultsr5   r5   r6   action_collect_logs  sn   






:"r  c                 C   s<  t }tttjtjtddtjtdd|d}|jdddd |jdd	t	 d
td d|j
_|jdddd}d|_|jddd}t| |jtd |jddd}t| |jtd |jddd}t| |jtd |jddd}t| |jtd |jddd}t| |jtd |jddd}	t|	| d  |	jtd |jd!d"d}
t|
| d  |
jtd |jd#d$d}|jtd t| |jd%d&d}t | |jt!d |jd'd(d}t"|| d  |jt#d |jd)d*d}|jt$d t%| |jd+d,d}|jt&d t'| |jd	d
td}|jt(d |S )-Nz	<command>r   )r,   r/   r-   r.   r+   z--debugr   z&show all debug log messages to consoler   z	--versionr   zshow version of {})r   r   r   r   r   rz   rM   r   Tr   z7attach this machine to an Ubuntu Advantage subscriptionr   r   r   z+automatically attach on supported platformsr   z%collect UA logs and debug informationr	   z5manage Ubuntu Advantage configuration on this machiner   z9remove this machine from an Ubuntu Advantage subscriptionr   z;disable a specific Ubuntu Advantage service on this machiner   r   z:enable a specific Ubuntu Advantage service on this machiner   z=check for and mitigate the impact of a CVE/USN on this systemr   z.list available security updates for the systemr   z9show detailed information about Ubuntu Advantage servicesr   z!refresh Ubuntu Advantage servicesr   z/current status of all Ubuntu Advantage services))__doc__r*   r   r^   r   r   rV   EPILOG_TMPLr   get_versionr   r   r   r   r   r   r   rk  r   re  r   r  r   r  r   rU  r   rF  r   rS  r   r   r   r   r   action_helpaction_refreshr   action_statusr   print_version)rL   r+   r   r   Zparser_attachZparser_auto_attachZparser_collect_logsZparser_configZparser_detachZparser_disableZparser_enableZ
parser_fixZparser_security_statusZparser_helpZparser_refreshZparser_statusZparser_versionr5   r5   r6   r     s   
r   c                C   sz  |st  }| r| jnd}| r| jnd }tjjj}|jrezt	
|r)|dtj W n: tjyd } z-t  tjjt|d}t| t| W d    n1 sUw   Y  W Y d }~nd }~ww tj|||d\}}t|d |k}	| r| jr|	r|d |krtjddd td tj|||d\}}|d |kstd t| t |}
tt!|
 t"  |S )	NFrM   )r   )simulate_with_token	show_betaZexecution_statusr?  )endr	  )#r	   rS   allr  r   ZUserFacingConfigStatusZACTIVEr   r}   r
   Zis_contract_changedZ
add_noticer   NOTICE_REFRESH_CONTRACT_WARNINGr   rK  r   disable_log_to_consoleZUPDATE_CHECK_CONTRACT_FAILURErV   r`   rL  rO  r   r   r   r&  waitr   timesleepZset_output_contentr_  r`  rC  )rf   rL   r  r   Zactive_valuerR  err_msgr   r   Zconfig_activera  r5   r5   r6   r  ;  sL   









r  c                 C   s   |d u rt  }tj|jdS )N)features)r	   rS   r   r  r  )_argsZ_cfgr5   r5   r6   r  a  s   r  c                 C   s   t t| | d S rV  )r   r  )r  rL   r5   r5   r6   r  h  s   r  c                 C   sr   z|   W n+ ty1 } zt  t| W d    n1 s"w   Y  ttj	d }~ww t
tj d S rV  )Zprocess_configRuntimeErrorr   r  rL  r   r   rw   r   ZREFRESH_CONFIG_FAILUREr   ZREFRESH_CONFIG_SUCCESS)rf   rL   excr5   r5   r6   _action_refresh_configl  s   
r  c                 C   sv   zt | W n, tjy3 } zt  t| W d    n1 s$w   Y  tt	j
d }~ww tt	j d S rV  )r
   rJ  r   rK  r   r  rL  r   rw   r   rN  r   ZREFRESH_CONTRACT_SUCCESSr  rL   r  r5   r5   r6   _action_refresh_contractv  s   
r  c                 C   sx   z	t | t  W n+ ty4 } zt  t| W d    n1 s%w   Y  tt	j
d }~ww tt	j d S rV  )r'   r&   	Exceptionr   r  rL  r   r   rw   r   ZREFRESH_MESSAGES_FAILUREr   ZREFRESH_MESSAGES_SUCCESSr  r5   r5   r6   _action_refresh_messages  s   

r  z
ua refreshc                C   sl   | j d u s
| j dkrt| | | j d u s| j dkr%t| | |dtj | j d u s/| j dkr4t| | dS )Nr	   r
   rM   r   r   )r   r  r  Zremove_noticer   r  r  r   r5   r5   r6   r    s   


r  scoper/  r0  c                 C   sR   |t jkr| j}| j}n|t jkr| j}| j}d|v r|}n|}t|||d dS )zS
    Handles setting part the apt proxies - global and uaclient scoped proxies
    r  )r  r  Zproxy_scopeN)r   r,  r  r  r(  r  r  r   )rL   r  r/  r0  r  r  r5   r5   r6   r'    s   


r'  c                C   s   | j }| j}|st|dj|d dS |st }t||}| jdkr-t	t
| dS | D ]\}}t	d| | q1dS )Nr   )rF   r   r(   z{}:
{}
)r{   r  r   rE   r	   rS   r   r   rV   r   r(   r   itemsr   )rf   rL   r{   rF   Zhelp_responser   r   r5   r5   r6   r    s   
r  c           
      C   s   |du rt  }|j}t }tt}|du rt }|	| g |_
ttj}|| |	|  |d || t dkrqt|}| sV|  |d t|}	|		| |	| |	d ||	 dS dS )z3Setup console logging and debug logging to log_fileNz
ua-consoler   i  zua-file)r	   rS   rx  r   ZLogFormatterrL  Z	Formatterr   Z	getLoggerZsetLevelhandlersZStreamHandlerr:   r;   ZsetFormatterZset_nameZ
addHandlerrp   rq   pathlibZPathexistsZtouchchmodZFileHandler)
console_level	log_levelrx  loggerrL   Zconsole_formatterZlog_formatterZconsole_handlerZlog_file_pathZfile_handlerr5   r5   r6   setup_logging  s2   











r  c                 C   s`   | j dv r*t| j  t| dr,| jdkrttjj | jdkr.ttjj	 dS dS dS dS )z3Set the right event mode based on the args provided)r   r   r   r   r   rV   r(   r)   N)
rz   r   Zset_commandhasattrrV   set_event_moder   ZEventLoggerModeZJSONZYAML)rx   r5   r5   r6   r    s   



r  c                    rc   )Nc                     s  z | i |W S  t y;   t  td W d    n1 s#w   Y  tdtjd t	  t
d Y d S  tjy } zdt|v rntj}tdrTtj}|j|jd}tj|j|jd tj|jtjd	 nDt # |j|d
}|jrtj}ntj}t|jdi | W d    n1 sw   Y  tj}tj|j|jd tj|jtjd	 t	  t  t
d W Y d }~d S d }~w tjy$ } zMt  t|j W d    n1 sw   Y  tj|j|j|jd tjd|jtjd	 t |tj!st	  t  t
|j" W Y d }~d S d }~w t#yu } zEt  td W d    n	1 sAw   Y  t	  tjtj$jtjd	 tjt%|dt|dd t  t
d W Y d }~d S d }~ww )NKeyboardInterruptzInterrupt received; exiting.r?   r	  ZCERTIFICATE_VERIFY_FAILEDzca-certificates)rN   rh  )Zinfo_msgrg  )rN   r>   )r   r   additional_infoz{}z&Unhandled exception, please file a bugrt   r   )r   Z
error_typer5   )&r  r   r  rL  r>   r   r:   r;   r   Zclear_lock_file_if_presentr<   r   rK  r`   r   Z&SSL_VERIFICATION_ERROR_CA_CERTIFICATESZis_installedZ%SSL_VERIFICATION_ERROR_OPENSSL_CONFIGrV   rN   r   rt   rJ   r   Z$LOG_CONNECTIVITY_ERROR_WITH_URL_TMPLZLOG_CONNECTIVITY_ERROR_TMPLr   ZCONNECTIVITY_ERRORrC  rw   ru   r  r   ZLockHeldErrorZ	exit_coder  ZUNEXPECTED_ERRORr~   )rf   rg   r  Ztmplrt   Zmsg_argsZmsg_tmplrR  funcr5   r6   rm     s|   






z#main_error_handler.<locals>.wrapperr5   )r  rm   r5   r  r6   main_error_handler  s   ?r  c           
      C   s  | st j} t }t|d}| dd  }|s#|  td t d |j|d}t	| |j
}|j}tj||d |j}|jrCtjntj}t|||j ttd|   t  |  W d    n1 sjw   Y  dd ttj D }	|	rttd	|	  |j||dS )
Nr   r	  z%Try 'ua --help' for more information.)rf   r  zExecuted with sys.argv: %rc                 S   s:   g | ]\}}|  tv s|d s|dkrd||qS )ZUA_FEATURESZUA_CONFIG_FILEz{}={})lowerr   
startswithrV   )r  kvr5   r5   r6   r  \  s    

zmain.<locals>.<listcomp>z*Executed with UA environment variables: %r)r:   argvr	   rS   r   r9   r   r<   
parse_argsr  r  r  r   Zconfigure_web_proxyr  rM  rL  DEBUGINFOr  rx  r{  r  Zwarn_about_invalid_keysrB   rp   environr  r   )
Zsys_argvrL   r   Zcli_argumentsrf   r  r  r  r  Zua_environmentr5   r5   r6   main?  sB   



r  __main__rV  )NN)r  r^   r(   rL  rp   r  r   r|  r:   r~  rv  rW   r  	functoolsr   typingr   r   r   r   r)   Zuaclientr   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r4  r   r   Zuaclient.cloudsr   r   Zuaclient.data_typesr   r   Zuaclient.defaultsr   r   r   r   r    Z(uaclient.entitlements.entitlement_statusr!   r"   r#   r$   r  r%   Zuaclient.jobs.update_messagingr&   r'   r   r   r  ZSTATUS_HEADER_TMPLr   r   ru  rw  Zget_event_loggerr   ArgumentParserr*   rn   rr   ry   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rS   r   r   r   r   r   r`   r   r  r   r   r   r;  rF  r&  ZNamedMessagerG  rS  r-  rU  rT  rb  re  rk  rq  r  r   r  r  r  r  r  r  r  r'  r  r  r  r  r  r[   r<   r5   r5   r5   r6   <module>   s  4
	
O
(''$O )
w
/)
A9?H
An
&




&C
,