Your IP : 216.73.216.14


Current Path : /usr/lib/python3/dist-packages/uaclient/__pycache__/
Upload File :
Current File : //usr/lib/python3/dist-packages/uaclient/__pycache__/cli.cpython-38.pyc

U

8�-d��@sPdZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZddl
mZmZmZddlmZmZmZmZmZmZmZmZmZmZmZddlmZddlmZm Z m!Z!ddlm"Z#dd	lm$Z$m%Z%dd
l&m'Z'ddl(m)Z)m*Z*ddl+m,Z,dd
l-m.Z.m/Z/ddl0m1Z1m2Z2ddl3m4Z4ddl5m6Z6m7Z7ddl8m9Z9m:Z:ddl;m<Z<ddl=m>Z>m?Z?m@Z@ddlAmBZBmCZCmDZDmEZEddlFmGZGmHZHddlImJZJddlKmLZLmMZMddlNmOZOddlPmQZQmRZRdZSdZTdZUdZVdZWdZXd d!d"gZYd#ZZd$ej[d%Z\e�]�Z^Gd&d'�d'ej_�Z`d�d(d)�Zad*d+�Zbd,d-�Zcd�d.d/�Zdd0d1�Zed2d3�Zfd4d5�Zgd6d7�Zheid8�d9d:�Zjeid8�d;d<�Zkeid8�d=d>�Zld?d@�ZmdAdB�ZndCdD�ZodEdF�ZpdGdH�ZqdIdJ�ZrdKdL�ZsdMdN�ZtejudO�dPdQ�ZvejudO�dRdS�ZwejudO�dTdU�ZxdVdW�ZydXdY�ZzdZd[�Z{ejueieid\�d]d^�Z|d_d`�dadb�Z}dcdd�Z~dedf�Zebdgdh��Z�ebdidj��Z�dkdl�Z�ecebede��eadm�dndo�����Z�ecebede��eadp�dqdr�����Z�ecebed�eads�e�dt�dudv�����Z�ejue�e�dw�dxdy�Z�ejuddz�d{d|�Z�d}d~�Z�ebejue�dz�dd���Z�d�d��Z�eeebead��d�d�����Z�ejudO�d�d��Z�ejudO�d�d��Z�ejudO�d�d��Z�d�d��Z�ejudO�d�d��Z�d�d�d��Z�ejudO�d�d��Z�ed�ejudO�d�d���Z�ejudO�d�d��Z�ebead��ejudO�d�d����Z�ejue6eieeidd��d�d��Z�d�d��Z�d�ddt�d�d��Z�d�d�d��Z�d�d��Z�d�d��Z�e�d�d�d���Z�e�d�k�rLe��e���dS)�z2Client to manage Ubuntu Pro services on a machine.�N��wraps)�List�Optional�Tuple)�actions�apt�apt_news�config�contract�daemon�defaults�entitlements�event_logger�
exceptions�lock)�log)�messages�security�security_status)�status)�util�version)�call_api)�FullAutoAttachOptions�_full_auto_attach)�	_initiate)�MagicAttachRevokeOptions�_revoke)�MagicAttachWaitOptions�_wait)�_reboot_required)�
AptProxyScope�setup_apt_proxy)�AttachActionsConfigFile�IncorrectTypeError)�PRINT_WRAP_WIDTH)�,create_enable_entitlements_not_found_message�entitlements_disable_order�get_valid_entitlement_names)�ApplicationStatus�CanDisableFailure�CanEnableFailure�CanEnableFailureReason)�notices�state_files)�Notice)�refresh_motd�update_motd_messages)�JsonArrayFormatter)�	safe_dump�	safe_load�proz{name} {command} [flags]zAUse {name} {command} --help for more information about a command.z&Try 'pro --help' for more information.z}Account: {account}
Subscription: {subscription}
Valid until: {contract_expiry}
Technical support level: {tech_support_level}
z$https://auth.contracts.canonical.comZtabular�json�yamlzua_logs.tar.gz�
z� A new version is available: {version}
Please run:
    sudo apt-get install ubuntu-advantage-tools
to get the latest version with new features and bug fixes.csleZdZdddejdfeed��fdd�
Zdd�Zd
�fdd	�	Z	e
eeeeefd
�dd��Z
�ZS)�UAArgumentParserN)�	base_desccst�j||||d�||_dS)N)�prog�usage�epilog�formatter_class)�super�__init__r;)�selfr<r=r>r?r;��	__class__��./usr/lib/python3/dist-packages/uaclient/cli.pyrAhs�zUAArgumentParser.__init__cCs,|�tj�|dkrt}|�d|d�dS)Nz&the following arguments are required: �r9)�print_usage�sys�stderr�TRY_HELP�exit)rB�messagerErErF�erroryszUAArgumentParser.errorFcsP|jr>t��\}}t|�}|r*t||�}d�|jg|�|_t�j|d�dS)Nr9��file)r;r:�_get_service_descriptions�sorted�join�descriptionr@�
print_help)rBrP�show_all�non_beta_services_desc�beta_services_descZservice_descriptionsrCrErFrU�s��
�zUAArgumentParser.print_help��returnc
	Cs�t��}d}g}g}t�t���}|D]�}ztj||dd�}Wntjk
rZYq&YnX|�d|d�}|j	r�d�
|j	�}nd}tj|j
||j
|d�tdd	d	d
�}	|jr�|�|	�q&|�|	�q&||fS)Nz - {name}: {description}{url}�name��cfgr[ZpresentedAsz ({})�)r[rT�urlz   F)�width�subsequent_indent�break_long_words�break_on_hyphens)r
�UAConfigrZget_available_resourcesr�entitlement_factoryr�EntitlementNotFoundError�getZhelp_doc_url�format�textwrap�fillrTr&Zis_beta�append)
r]Zservice_info_tmplrWrXZ	resources�resource�ent_clsZpresentation_namer_Zservice_inforErErFrQ�s@�

��z*UAArgumentParser._get_service_descriptions)NF)�__name__�
__module__�__qualname__�argparseZ
HelpFormatterr�strrArNrU�staticmethodrrrQ�
__classcell__rErErCrFr:gs��r:cs�fdd�}|S)z1Decorator asserting exclusive access to lock filecst����fdd��}|S)Nc	s0tj|�d���|d|i|��}W5QRX|S)N)r]�lock_holderr])rZSingleAttemptLock)r]�args�kwargsZretval)�frurErF�new_f�sz0assert_lock_file.<locals>.wrapper.<locals>.new_fr�rxry�ru�rxrF�wrapper�sz!assert_lock_file.<locals>.wrapperrE)rur}rEr{rF�assert_lock_file�s	r~cst���fdd��}|S)zDecorator asserting root usercs t��st���n
�||�SdS�N)r�we_are_currently_rootrZNonRootUserError)rvrwr|rErFry�s
zassert_root.<locals>.new_frrzrEr|rF�assert_root�sr�cst���fdd��}|S)z>Decorator to verify if correct params are used for json formatcsR|s�|f|�|�S|jdkr>|js>tj}tj|j|jd��n�|f|�|�SdS)Nr7��msg�msg_code)rh�
assume_yesrZJSON_FORMAT_REQUIRE_ASSUME_YESr�UserFacingErrorr�r[)�cmd_argsrvrwr�r|rErFry�sz&verify_json_format_args.<locals>.new_frrzrEr|rF�verify_json_format_args�s
r�cs�fdd�}|S)z�Decorator asserting attached config.
    :param msg_function: Optional function to generate a custom message
    if raising an UnattachedError
    cst����fdd��}|S)Ncs\|jsH�r<t|dd�}t|dd�}�|||d�}t�|�}nt��}|��|fd|i|��S)N�commandr^�service)r��
service_namesr]r])�is_attached�getattrrZUnattachedError)rvr]rwr�r�r��	exception)rx�msg_functionrErFry�s�z/assert_attached.<locals>.wrapper.<locals>.new_frrz�r�r|rFr}�sz assert_attached.<locals>.wrapperrE)r�r}rEr�rF�assert_attached�sr�cst���fdd��}|S)z&Decorator asserting unattached config.cs(|jrt�|jj�dd����||d�S)Nr[r^�r])r�rZAlreadyAttachedError�machine_token_fileZaccountrg�rvr]r|rErFry
s
�z"assert_not_attached.<locals>.new_frrzrEr|rF�assert_not_attached
sr�cCs4d|_d|_|jdddd�|jddgd	d
d�|S)z5Build or extend an arg parser for the api subcommand.�api�Calls the Client API endpoints.�
endpoint_pathZendpointzAPI endpoint to call)�metavar�helpz--args�options�*z;Options to pass to the API endpoint, formatted as key=value)�dest�default�nargsr�)r<rT�add_argument��parserrErErF�
api_parsers��r�cCs*d|_d|_tjt|jd�|_d|j_|S)z9Build or extend an arg parser for auto-attach subcommand.�auto-attachz5Automatically attach on an Ubuntu Pro cloud instance.�r[r��Flags)r<rT�
USAGE_TMPLrh�NAMEr=�
_optionals�titler�rErErF�auto_attach_parser)s�r�cCs2d|_d|_tjt|jd�|_|jdddd�|S)z<Build or extend an arg parser for 'collect-logs' subcommand.�collect-logsz<Collect logs and relevant system information into a tarball.r�z-oz--outputzEtarball where the logs will be stored. (Defaults to ./ua_logs.tar.gz)�r�)r<rTr�rhr�r=r�r�rErErF�collect_logs_parser4s��r���parent_commandcCs6tjtd�|�d�|_d|_d|_|jdddd�|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.�r�r�)r�rhr�r=r<rTr��r�r�rErErF�config_show_parserFs��r�cCsJtjtd�|�d�|_d|_d|_d|j_|jdd�d�	t
j��d	�|S)
z:Build or extend an arg parser for 'config set' subcommand.z{} set <key>=<value>r�Zasetz/Set and apply Ubuntu Pro configuration settingsr��key_value_pairzKkey=value pair to configure for Ubuntu Pro services. Key must be one of: {}�, r�)r�rhr�r=r<rTr�r�r�rSr
�UA_CONFIGURABLE_KEYSr�rErErF�config_set_parserUs�
��	r�cCsLtjtd�|�d�|_d|_d|_|jdd�d�tj	��dd�d	|j
_|S)
z<Build or extend an arg parser for 'config unset' subcommand.z{} unset <key>r��unsetz&Unset Ubuntu Pro configuration settingr�z?configuration key to unset from Ubuntu Pro services. One of: {}r�)r�r�r�)r�rhr�r=r<rTr�rSr
r�r�r�r�rErErF�config_unset_parseris�
��r�cCs�d}tjtd�|�d�|_||_d|_d|j_|jdddd	�}|j	d
dd�}|j
td
�t||d�|j	ddd�}|j
t
d
�t||d�|j	ddd�}|j
td
�t||d�|S)z4Build or extend an arg parser for config subcommand.r
z{} <command>r�zManage Ubuntu Pro configurationr��Available Commandsr�r^�r�r�r�r�z,show all Ubuntu Pro configuration setting(s)r���actionr��setz$set Ubuntu Pro configuration settingr�z&unset Ubuntu Pro configuration setting)r�rhr�r=r<rTr�r��add_subparsers�
add_parser�set_defaults�action_config_showr��action_config_setr��action_config_unsetr�)r�r��
subparsersZparser_showZ
parser_setZparser_unsetrErErF�
config_parser|s@�����r�cCs�tjtdd�|_tj|_d|_d�tj	�}|dd|_
d|j_|j
dd	d
�t�d�|j
dd
ddd�|j
dt�d�dd�|j
ddddgddd�|S)z4Build or extend an arg parser for attach subcommand.zattach <token>r��attachz@Attach this machine to Ubuntu Pro with a token obtained from:
{}z

z�When running this command without a token, it will generate a short code
and prompt you to attach the machine to your Ubuntu Pro account using
a web browser.r��tokenr�z0token obtained for Ubuntu Pro authentication: {}r�z--no-auto-enableZstore_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�clir7�4output enable in the specified format (default: cli)�r��choicesr�r�)r�rhr�r=rq�RawDescriptionHelpFormatterr?r<r
�BASE_UA_URLrTr�r�r��UA_AUTH_TOKEN_URLZFileType)r�r;rErErF�
attach_parser�sP�����	�����r�cCsFtjtdd�|_d|_d|_d|j_|jddd�|jd	d
dd�|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�z	--dry-run�
store_truezrIf used, fix will not actually run but will display everything that will happen on the machine during the command.�r�r��	r�rhr�r=r<rTr�r�r�r�rErErF�
fix_parser�s$����
r�cCsxd|_tj|_t�d�|_|jddddd�|��}|jdd	d
d�|jdd
d
d�|jddd
d�|jddd
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 Expanded Security Maintenance (ESM) related content.

        Shows counts of how many packages are supported for security updates
        in the system.

        If called with --format json|yaml it shows a summary of the
        installed packages based on the origin:
        - main/restricted/universe/multiverse: packages from the Ubuntu archive
        - esm-infra/esm-apps: packages from the ESM archive
        - 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 output contains basic information about Ubuntu Pro. For a
        complete status on Ubuntu Pro services, run 'pro status'.
        r�zFormat for the output)r7r8�textr�)r�r�r�z--thirdpartyz7List and present information about third-party packagesr�)r�r�z
--unavailablez7List and present information about unavailable packagesz--esm-infraz5List and present information about esm-infra packagesz
--esm-appsz4List and present information about esm-apps packages)	r<rqr�r?ri�dedentrTr�Zadd_mutually_exclusive_group)r��grouprErErF�security_status_parser�sB������r�cCsVd|_d|_tjtdd�|_d|j_tj	|_
t�d�|_|j
ddd	d
gddd
d�|S)z5Build or extend an arg parser for refresh subcommand.�refreshz9Refresh existing Ubuntu Pro contract and update services.z"refresh [contract|config|messages]r�r�a�        Refresh three distinct Ubuntu Pro related artifacts in the system:

        * contract: Update contract details from the server.
        * config:   Reload the config file.
        * messages: Update APT and MOTD messages related to UA.

        You can individually target any of the three specific actions,
        by passing it's target to nome to the command.  If no `target`
        is specified, all targets are refreshed.
        �targetrr
rr�NzTarget to refresh.)r�r�r�r�)r<rTr�rhr�r=r�r�rqr�r?rir�r�r�rErErF�refresh_parser&s(���
�r�cKs�|jdkrZ|jrt��q�|jr*t��q�|jr<t�|�q�|jrNt�	|�q�t�|�n>|jdkr�t
tjt�
|�dtjd��nt
tt�
|�dd��dS)Nr�r7T)Z	sort_keys�clsF)Zdefault_flow_styler)rhZ
thirdpartyrZlist_third_party_packagesZunavailableZlist_unavailable_packagesZ	esm_infraZlist_esm_infra_packagesZesm_appsZlist_esm_apps_packages�printr7�dumpsZsecurity_status_dictrZDatetimeAwareJSONEncoderr4�rvr]rwrErErF�action_security_statusIs2



����r�cKs@t�tj|j�s&d�|j�}t�|��tj||j|j	d�}|j
S)NzYError: issue "{}" is not recognized.
Usage: "pro fix CVE-yyyy-nnnn" or "pro fix USN-nnnn")r]Zissue_id�dry_run)�re�matchrZCVE_OR_USN_REGEXr�rhrr�Zfix_security_issue_idr��value)rvr]rwr�Z
fix_statusrErErF�
action_fixgs��
�r�cCsTtjtdd�}||_d|_d|_d|j_|jdddd�|jd	d
ddgdd
d�|S)z4Build or extend an arg parser for detach subcommand.�detachr�z-Detach this machine from Ubuntu Pro services.r��--assume-yesr�z;do not prompt for confirmation before performing the detachr�r�r�r�r7r�r�r��r�r=rErErF�
detach_parserws$��r�r�cCs�tjtdd�}||_d|_d|_d|j_|jdddd	�d
�	t
j|d���d�|jd
dttdd�td�d�|jdddd�|S)z2Build or extend an arg parser for help subcommand.zhelp [service]r�r�z7Provide detailed information about Ubuntu Pro services.�	Argumentsr�r�r�z-a service to view help output for. One of: {}r�r��r�r�r�r�rz1output help in the specified format (default: {})r��--allr��(Allow the visualization of beta servicesr�)
r�rhr�r=r<rT�_positionalsr�r�rSr�valid_services�STATUS_FORMATS�r�r]r=rErErF�help_parser�s:���	���r�cCs�tjtdd�}d|_||_d|_d|j_d|j_|j	ddd	d
�d�
tj|d���d
�|j	dddd�|j	dddd�|j	dddd�|j	ddddgddd�|S)z4Build or extend an arg parser for enable subcommand.zenable <service> [<service>]r�zEnable an Ubuntu Pro service.�enabler�r�r�r��+z<the name(s) of the Ubuntu Pro services to enable. One of: {}r�r�r�r�r�z;do not prompt for confirmation before performing the enabler�z
--access-onlyzHdo not auto-install packages. Valid for cc-eal, cis and realtime-kernel.z--betaz allow beta service to be enabledr�r�r7r�r��
r�rhr�rTr=r<r�r�r�r�rSrr�r�rErErF�
enable_parser�sP�������rcCs�tjtdd�}d|_||_d|_d|j_d|j_|j	ddd	d
�d�
tj|d���d
�|j	dddd�|j	ddddgddd�|S)z5Build or extend an arg parser for disable subcommand.zdisable <service> [<service>]r�zDisable an Ubuntu Pro service.�disabler�r�r�r�r�z=the name(s) of the Ubuntu Pro services to disable. One of: {}r�r�r�r�r�z<do not prompt for confirmation before performing the disabler�r�r�r7z5output disable in the specified format (default: cli)r�rr�rErErF�disable_parser�s<�����rcCsZtjtdd�|_d|_d|_d|j_|jdddd	�}|j	d
dd�}|j
td
�t|�|S)z4Build or extend an arg parser for system subcommand.zsystem <command>r�z9Output system related information related to Pro services�systemr�r�r�r^r��reboot-requiredz#does the system need to be rebootedr�r�)
r�rhr�r=rTr<r�r�r�r�r��action_system_reboot_required�reboot_required_parser)r�r�Zparser_reboot_requiredrErErF�
system_parsers"���rcCs.tjtdd�|_d|_tj|_t�	d�|_
|S)Nzsystem reboot-requiredr�ral        Report the current reboot-required status for the machine.

        This command will output one of the three following states
        for the machine regarding reboot:

        * no: The machine doesn't require a reboot
        * yes: The machine requires a reboot
        * yes-kernel-livepatches-applied: There are only kernel related
          packages that require a reboot, but Livepatch has already provided
          patches for the current running kernel. The machine still needs a
          reboot, but you can assess if the reboot can be performed in the
          nearest maintenance window.
        )r�rhr�r=r6rqr�r?rir�rTr�rErErFrs��rc	Cs�tjtdd�}||_d|_d|_tj|_t	�
d�|_|jddddd	�|jd
dttdd
�td�d�|jddddd�|jdddd�d|j
_|S)z4Build or extend an arg parser for status subcommand.rr�z6Output the status information for Ubuntu Pro services.u;        Report current status of Ubuntu Pro 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 pro to complete)r�r�r�r�r�rz3output status in the specified format (default: {})r�z--simulate-with-tokenZTOKENz1simulate the output status using a provided token)r�r�r�r�r�r�r�)r�rhr�r=rTr<rqr�r?rir�r�r�r�r�r�rErErF�
status_parser5sJ��%�����r	)r]�cmd_name�subcmd_namecCsft|d�}|��dj|}|��dj��}||krb|��dj|��t�d�d�|����dS)Nr�rz
<command> must be one of: {}r�)	�
get_parser�_get_positional_actionsr��keysrUrr�rhrS)r]r
rr��	subparserZ
valid_choicesrErErF�_print_help_for_subcommand�s
�rT)�
update_statuscCs�|��\}}|sbt�|j�|dk	rnt|t�rn|jdk	rnt�|jj�tj	|jj|jj|jd�nt�
|j�|r~tj|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_failedr[�
isinstancer+rM�infor�rN�service_processed�	ua_statusr)�entitlementr]r�r�ret�reasonrErErF�_perform_disable�s

�rcKst|d|jd�dS)zGPerform the config action.

    :return: 0 on success, 1 otherwise
    r
�r
rr�rr�r�rErErF�
action_config�s�r!cKs�|jrr|jtjkrPd�|jd�tj��}|�d�d}t�tj	|t
d|d���tdj|jt||jd�d	��d
St
tdd�tjD��d
�}d|d}tjD]}t|j|t||d�d	��q�|js�|jr�|js�|jr�td�dS)z�Perform 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��:rG� )r`raz
{key} {value}N)r�r�rcSsg|]}t|��qSrE)�len)�.0�xrErErF�
<listcomp>�sz&action_config_show.<locals>.<listcomp>�z{key: <z	} {value}zo
Error: Setting global apt proxy and pro scoped apt proxy at the same time is unsupported. No apt proxy is set.)r�r
r�rhrS�findrr�rirjr&r�r�rr�max�global_apt_http_proxy�global_apt_https_proxy�ua_apt_http_proxy�ua_apt_https_proxy)rvr]rwr�Zindent_positionZ	col_widthZrow_tmplr�rErErFr��sB
�����
���r�c	Ks&ddlm}ddlm}t|d�}|��djd}|��djd}z|j�d�\}}	Wn.t	k
r�|�
�t�d�
|j���YnX|tjkr�|�
�t�d	�
d
�tj����|dk�r4|�d�d}
|
d
kr�tj}ntj}t�|
|	|�||	i}|f|�tj�|�}|��\}
}|
tjk�r|f|��n�||jk�r�|�d�d}
|
d
k�r`tj}ntj}t�|
|	|�t|j�p�|j �}|�r�t!t"j#j
ddd��t$|t%j&||	�d|_d|_ �nV||j'|j(k�rzd|k�r�dnd
}
|
d
k�r�tj}ntj}||j'k�r"t!t"j)j
|
d��d|}t�|
|	|�t|j*�p>|j+�}|�r\t!t"j#j
ddd��t$|t%j,||	�d|_*d|_+n�|dk�r�z$t-|	�}	|	dk�r�t	d�
|���Wn8t	k
�r�|�
�t!d�t�d�
||	���YnXn2|dk�r|	�.�dk}	|	�rt/�0|�n
t1j2�3�t4|||	�dS)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�_�httprGzpro scoped aptz
global apt)Z
current_proxyZprevious_proxyN�https��
protocol_type�global_)Zupdate_messaging_timerZmetering_timerzInvalid interval for {}r^zECannot set {} to {}: <value> for interval must be a positive integer.r	�true)5�uaclient.livepatchr/�
uaclient.snapr0rr
r�r��split�
ValueErrorrUrr�rhr
r�rSrZPROXY_VALIDATION_SNAP_HTTP_URLZPROXY_VALIDATION_SNAP_HTTPS_URLZvalidate_proxyr�	livepatch�LivepatchEntitlement�application_statusr*�ENABLED�ua_scoped_proxy_optionsZPROXY_VALIDATION_APT_HTTP_URLZPROXY_VALIDATION_APT_HTTPS_URL�boolr+r,r�rZWARNING_APT_PROXY_OVERWRITE�configure_apt_proxyr"�UACLIENT�&deprecated_global_scoped_proxy_options�global_scoped_proxy_options�WARNING_APT_PROXY_SETUPr-r.�GLOBAL�int�lowerr	�update_apt_newsr/Zapt_news_contents_file�delete�setattr)rvr]rwr/r0r�r�r�set_key�	set_valuer:Zvalidate_urlr�livepatch_statusr6Z
unset_currentrErErFr��s�
��


��


���
��
����

���

r�c
Ksjddlm}ddlm}ddlm}|jtjkr~t	|d�}|�
�djd}|�
�djd}|��t
�d�d	�tj����|jd
kr�|j�d�d}	||	d�tj�|�}
|
��\}}|tjkr�||	d�n�|j|jkr�t||j|jd
�nh|j|j|jk�rX|j|jk�rFd|jk�r"dnd}	t�tj j|	d��d|j|_t||j!|jd
�t"||jd
�dS)zOPerform the 'config unset' action.

    @return: 0 on success, 1 otherwise
    r)r")�unconfigure_livepatch_proxy)�unconfigure_snap_proxyr�r
r�r2r�r3r6r9Nr8r7r;)#�uaclient.aptr"r=rUr>rVr�r
r�rr
r�rUrr�rhrSr?rrArBrCr*rDrErGrHrIrJrrrrKrLrQ)
rvr]rwr"rUrVr�r�rr:rrTr6rErErFr�csL

��


����r�cCs|t||d�\}}|r>|r>tj}|jd�|�|d�|�dd�}n:|rXtjjd�|�d�}n tjj|d�|�d�tj�d�}|S)z�Generates a custom message for enable/disable commands when unattached.

    Takes into consideration if the services exist or not, and notify the user
    accordingly.)�namesr]r�r^)�
valid_service�	operation�invalid_service�service_msg)rYzSee {}�rZr[r\)	r)rZ!MIXED_SERVICES_FAILURE_UNATTACHEDrhrSZ VALID_SERVICE_FAILURE_UNATTACHEDZINVALID_SERVICE_OP_FAILUREr
r�)r�r�r]�entitlements_found�entitlements_not_foundr�rErErF�%_create_enable_disable_unattached_msg�s,�
��
�r`zpro disablecKs�t|dg�}t||�\}}d}|D]4}tj||d�}|||jd�}	|t|	||jd�M}q"|r�dd�tj|dd��d}
d	�tj	|
d
ddd��}t
jd
d�|�|d��t�
�|r�dSdS)zbPerform the disable action on a list of entitlements.

    @return: 0 on success, 1 otherwise
    r�Tr\�r�zTry r��r]�
allow_beta�.r9�PF)r`rbrcrr]rr()r�r)rrer�rrSr�riZwraprZInvalidServiceToDisableErrorr�process_events)rvr]rwrXr^r_r�ent_namerm�entZvalid_namesr\rErErF�action_disable�s@	�������riz
pro enablecKs�t�tj�zt�|�Wn:tjtjfk
rTt	j
tjdd�tjtjd�YnXt
|dg�}t||�\}}d}|D�]}z�tj|||j|j|jd�\}}	tj|d�|�s|	dk	�rt|	t��r|	jdk	r�t�|	jj�tj|	jj|	jj|d�|	jtjk�r@|�|�n0|�r$tj |d	�n|�s@|	dk�r@tj!|d	�||M}Wqxtjk
�r�}
z(t�|
j�tj|
j|
j"|d�d
}W5d}
~
XYqxXqx|�r�t#|||jd�}t�$|�tj|j|jd��t�%�|�r�d
SdS)z^Perform the enable action on a named entitlement.

    @return: 0 on success, 1 otherwise
    T)�exc_info)Zwarning_msgr�)r�rc�access_onlyr�Nr)r�Frbr�rr()&rrrZREFRESH_CONTRACT_ENABLEr�request_updated_contractr�UrlErrorr��logging�debug�REFRESH_CONTRACT_FAILURE�warningr�r)r�enable_entitlement_by_namer�Zbetarkrrrr,rMr�rNr[rr-ZIS_BETArkrrr�r'Zservices_failedrf)rvr]rwrXr^r_rrg�ent_retr�er�rErErF�
action_enable�sx	�
�
���
���
ruz
pro detachrYcCs*t||jd�}|dkrt��t��|S)zXPerform the detach action for this machine.

    @return: 0 on success, 1 otherwise
    rar)�_detachr�r�startrrf)rvr]rrErErF�
action_detach&s
	rx)r]r�rZc		Csg}t|�D]\}ztj||d�}Wntjk
r<YqYnX|||d�}|jdd�\}}|r|�|�q|r�t|�dkr~dnd}t�	d�
|��|D]}t�	d	�
|j��q�tj
|d
�s�dS|D]}t|||dd�q�|��|j��t|�t�	tj�d
S)a7Detach the machine from the active Ubuntu Pro 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
    r\)r]r�T)Zignore_dependent_servicesr(�sr^z,Detach will disable the following service{}:z    {}raF)r�rr)r(rrerrfZcan_disablerkr$rrrhr[rZprompt_for_confirmationrZdelete_cacher�rPr2rZDETACH_SUCCESS)	r]r�Z
to_disablergrmrhrr6�suffixrErErFrv6s4

�
rv)r]rZcCs�d}|jr&|j�di��di��d�}|r@t�tjj|d��nt�tj�t�	�t�
|�t�|�\}}t
�|�}t�t�|��t��dS)NZmachineTokenInfoZcontractInfor[)�
contract_name)Z
machine_tokenrgrrrZATTACH_SUCCESS_TMPLrhZATTACH_SUCCESS_NO_CONTRACT_NAMEr�stopZcleanuprrr�format_tabularr�handle_unicode_charactersrf)r]r{rZ_ret�outputrErErF�_post_cli_attachbs(����

r�cCs.t|j|j|�}t|���|jdkr*dSdS)NZsuccessrr()rr�r�r�Zto_json�result�rvr]r�rErErF�
action_api|sr�cCsPztt�|tjjd�Wn&tjk
r>t�t	j
j�YdSXt|�dSdS)N)r]�moder(r)
rrr�EventLoggerModeZCLIrrmrrrZATTACH_FAILUREr�r�r�rErErF�action_auto_attach�s�
r�c
Ks�|jdkrtjd|jd��t�tj�t|d�}t�dtjj|j	d��t
|jd�}zt||d�}WnLtj
k
r�}z,t�tj�t|jd�}t||d�|�W5d}~XYnXt�dtj�|jS)	Nr7r�)Zparamr�r�r9)�	user_code)Zmagic_token)r�r])rhrZMagicAttachInvalidParamrrrZCLI_MAGIC_ATTACH_INITrZCLI_MAGIC_ATTACH_SIGN_INr�rr�r ZMagicAttachTokenErrorZCLI_MAGIC_ATTACH_FAILEDrrZCLI_MAGIC_ATTACH_PROCESSINGZcontract_token)rvr]rwZ
initiate_respZwait_optionsZ	wait_resprtZrevoke_optionsrErErF�
_magic_attach�s4
�
����r�z
pro attachc
Cs�|jr$|jr$tjtjjtjjd��n�|jsB|jsBt||d�}d}nj|jrT|j}d}nXzt	�
t|j��}Wn6tk
r�}ztj
|jj|jd��W5d}~XYnX|j}|j}|jo�|dk}ztj|||d�Wntjk
r�t���Yn�Xd}|dk	�r�|j�r�t||�\}}	|D]z}
tj||
ddd�\}}|�s�d}|dk	�r�t|t��r�|jdk	�r�t�|jj�tj|jj|jj|
d	�n
t�|
��q|	�r�t|	|dd
�}
tj|
jtjd�tj|
j|
jd�d}t |�|SdS)
Nr�r�)Zconfig_namerN)r��allow_enablerT)r�rcr(rrb)�	file_type�rr)!r��
attach_configrr�rZATTACH_TOKEN_ARG_XOR_CONFIGr�r[r�r$Z	from_dictr5r%ZAttachInvalidConfigFileErrorZenable_servicesr�rZattach_with_tokenrmZAttachErrorr)rrrr,rMrrrNrr'rIrJr�)rvr]r�Zenable_services_overrider�rtr�r�foundZ	not_foundr[rsrr�rErErF�
action_attach�s������
�����r�cCs�|jpt}t���z}t�||�z*t�|d��}|j|dd�W5QRXWn<t	k
r�}zt
�|�WY�W5QR�dSd}~XYnXW5QRXdS)Nzw:gzzlogs/)Zarcnamer(r)r�UA_COLLECT_LOGS_FILE�tempfileZTemporaryDirectoryrZcollect_logs�tarfile�open�add�PermissionErrorrnrN)rvr]Zoutput_fileZ
output_dirZresultsrtrErErF�action_collect_logs�s


,r�cCs�t}tttjtjtdd�tjtdd�|d�}|jdddd�|jdd	t	�
�d
�t�d�d|j_|j
d
ddd�}d|_|jddd�}t|�|jtd�|jddd�}t|�|jtd�|jddd�}t|�|jtd�|jddd�}t|�|jtd�|jddd�}t|�|jtd�|jddd�}	t|	�|	jtd�|jd d!d�}
t|
|d"�|
jtd�|jd#d$d�}t||d"�|jt d�|jd%d&d�}|jt!d�t"|�|jd'd(d�}
t#|
�|
jt$d�|jd)d*d�}t%||d"�|jt&d�|jd+d,d�}|jt'd�t(|�|jd-d.d�}|jt)d�t*|�|jd	d
�t�d�}|jt+d�|jd/d0d�}|jt,d�t-|�|S)1Nz	<command>r�)r<r?r=r>r;z--debugr�z&show all debug log messages to consoler�z	--versionrzshow version of {})r�rr�r�r�r�r^r�Tr�z1attach this machine to an Ubuntu Pro subscriptionr�r�r�r�r�z+automatically attach on supported platformsr�z&collect Pro logs and debug informationr
z/manage Ubuntu Pro configuration on this machiner�z3remove this machine from an Ubuntu Pro subscriptionrz5disable a specific Ubuntu Pro service on this machiner�r�z4enable a specific Ubuntu Pro 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�z3show detailed information about Ubuntu Pro servicesr�zrefresh Ubuntu Pro servicesrz)current status of all Ubuntu Pro servicesrz/show system information related to Pro services).�__doc__r:r�rqr�r�rh�EPILOG_TMPLr�r�get_versionr�r�r�Zrequiredr�r�r�r�r�r�r�r�r�r�r�r!r�rxrrirrur�r�r�r�r��action_help�action_refreshr��
action_statusr	�
print_version�
action_systemr)r]r;r�r�Z
parser_attachZ
parser_apiZparser_auto_attachZparser_collect_logsZ
parser_configZ
parser_detachZparser_disableZ
parser_enableZ
parser_fixZparser_security_statusZparser_helpZparser_refreshZ
parser_statusZparser_versionZ
parser_systemrErErFrs��������������������rc	Cs�|st��}|r|jnd}|r$|jnd}tjjj}tj	|||d�\}}t
|d|k�}|r�|jr�|r�|d|kr�tj
ddd�t�d�tj	|||d�\}}qdt�
d�t�|�t�|�}t�
t�|��t��|S)NF)�simulate_with_tokenrVZexecution_statusrdr^)�endr()r
rd�allr�rZUserFacingConfigStatusZACTIVEr�rrrF�waitrr�time�sleepZset_output_contentr}rr~rf)	rvr]rVr�Zactive_valuerrZ
config_activerrErErFr��s4
�

�


r�cKst|d|jd�dS)zGPerform the system action.

    :return: 0 on success, 1 otherwise
    rrrr r�rErErFr��s�r�cCst|�}t�|j�dS)Nr)r!rrZreboot_requiredr�rErErFr�srcCstt���dSr)r�rr�)�_argsr]rErErFr��sr�cCshz|��WnLtk
rX}z.t���t�|�W5QRXt�tj	��W5d}~XYnXt
tj�dSr)Zprocess_config�RuntimeErrorr�disable_log_to_consolernr�rr�rZREFRESH_CONFIG_FAILUREr�ZREFRESH_CONFIG_SUCCESS)rvr]�excrErErF�_action_refresh_config�s
r�cCslzt�|�WnNtjk
r\}z.t���t�|�W5QRXt�t	j
��W5d}~XYnXtt	j�dSr)
rrlrrmrr�rnr�r�rrpr�ZREFRESH_CONTRACT_SUCCESS�r�r]r�rErErF�_action_refresh_contract�s
r�cCs~z"t|�t�|jr t�|�WnLtk
rn}z.t���t�|�W5QRXt	�
tj��W5d}~XYnXt
tj�dSr)r2r1r	rO�	Exceptionrr�rnr�rr�rZREFRESH_MESSAGES_FAILUREr�ZREFRESH_MESSAGES_SUCCESSr�rErErF�_action_refresh_messages�s
r�zpro refreshcCsj|jdks|jdkrt||�|jdks2|jdkrHt||�t�tj�|jdks\|jdkrft||�dS)Nr
rrr)r�r�r�r.�remover0ZCONTRACT_REFRESH_WARNINGr�r�rErErFr��s


r�)r]�scoperRrSrZcCsR|tjkr|j}|j}n|tjkr.|j}|j}d|kr<|}n|}t|||d�dS)zS
    Handles setting part the apt proxies - global and uaclient scoped proxies
    r8)r4r5Zproxy_scopeN)r"rLr+r,rHr-r.r#)r]r�rRrSr4r5rErErFrG�s	

�rGcCs�|j}|j}|s&t|d�j|d�dS|s2t��}t�||�}|jdkrXt	t
�|��n&|��D]\}}t	d�|�
�|��q`dS)Nr�)rVrr7z{}:
{}
)r�r�rrUr
rdrr�rhr�r7r��itemsr�)rvr]r�rVZ
help_responser�r�rErErFr�s
r�cCsD|r|jdkst|dd�dkr"dSt��}|r@t�tj|d��dS)Nr�rhr^)r7r8)r)r�r�rZcheck_for_new_versionrnrq�NEW_VERSION_NOTICErh)r�Znew_versionrErErF�_warn_about_new_versions���r�c	Cs�|dkrt��}|j}t��}|dkr.t��}|�|�|�t	�
��g|_t�t
j�}|�|�|�|�|�d�|�|�t��r�t�|�}|��s�|��|�d�t�|�}|�t��|�|�|�d�|�|�dS)z3Setup console logging and debug logging to log_fileNz
ua-consolei�zua-file)r
rd�log_filerZLogFormatterrnZ	getLoggerZsetLevelZ	addFilter�pro_logZRedactionFilterZhandlersZ
StreamHandlerrIrJZsetFormatterZset_nameZ
addHandlerr��pathlib�Path�existsZtouch�chmodZFileHandlerr3)	�
console_level�	log_levelr�Zloggerr]Zconsole_formatterZconsole_handlerZ
log_file_pathZfile_handlerrErErF�
setup_logging*s0









r�cCsT|jdkrPt�|j�t|d�rP|jdkr8t�tjj�|jdkrPt�tjj	�dS)z3Set the right event mode based on the args provided)r�r�r�rrrhr7r8N)
r�rZset_command�hasattrrh�set_event_moderr�ZJSONZYAML)r�rErErFr�Ps



r�cs�fdd�}|S)Ncs�z�||�WStk
r`t���t�d�W5QRXtdtjd�t�	�t�
d�Y�n>tjk
�rl}z�dt
|�kr�tj}t�d�r�tj}|j|jd�}tj|j|jd�tj|jtjd	�npt���8|j|d
�}|jr�tj}ntj}t�|jf|��W5QRXtj}tj|j|jd�tj|jtjd	�t�	�t��t�t�
d�W5d}~XY�n2tjk
�r}z�t���t�|j�W5QRXtj|j|j |j!d�tjd�|j�tjd	�t"|tj#��s�t�	�t��t�t�
|j$�W5d}~XYn�t%k
�r�}zpt���t�d
�W5QRXt�	�tjtj&jtjd	�tjt'|dt
|��dd�t��t�t�
d�W5d}~XYnXdS)N�KeyboardInterruptzInterrupt received; exiting.rOr(ZCERTIFICATE_VERIFY_FAILEDzca-certificates)r_r�)Zinfo_msgr�)r_rN)rr�additional_infoz{}z&Unhandled exception, please file a bugr�r�)rZ
error_type)(r�rr�rnrNr�rIrJrZclear_lock_file_if_presentrLrrmrrrZ&SSL_VERIFICATION_ERROR_CA_CERTIFICATESrZis_installedZ%SSL_VERIFICATION_ERROR_OPENSSL_CONFIGrhr_rr�r[rZ$LOG_CONNECTIVITY_ERROR_WITH_URL_TMPLZLOG_CONNECTIVITY_ERROR_TMPLr�ZCONNECTIVITY_ERRORrfr�r�r�r�rZ
LockHeldErrorZ	exit_coder�ZUNEXPECTED_ERRORr�)rvrwr�Ztmplr�Zmsg_argsZmsg_tmplrt��funcrErFr}\sv


�
�
��z#main_error_handler.<locals>.wrapperrE)r�r}rEr�rF�main_error_handler[sHr�c	Cs
|s
tj}t��}t|d�}|dd�}|sF|��tt�t�d�|j	|d�}t
|�|j}|j}t
j||d�|j}|jr�tjntj}t|||j�t�d|�t
���|��W5QRXdd�tt
�����D�}	|	r�t�d|	�|j||d�}
t|�|
S)	Nr�r()rvr3zExecuted with sys.argv: %rcSsg|]\}}d�||��qS)z{}={})rh)r%�k�vrErErFr'�s�zmain.<locals>.<listcomp>z'Executed with environment variables: %r)rI�argvr
rdrrHr�rKrL�
parse_argsr�r4r5rZconfigure_web_proxyr�rorn�DEBUG�INFOr�r�r�Zwarn_about_invalid_keysrRZget_pro_environmentr�r�r�)Zsys_argvr]r�Z
cli_argumentsrvr4r5r�r�Zpro_environmentZreturn_valuerErErF�main�s<


��r��__main__)N)N)NN)N)NN)N)�r�rqr7rnr�r�rIr�r�rir��	functoolsr�typingrrrZuaclientrrr	r
rrr
rrrrrr�rrrrrrrZuaclient.api.apirZ2uaclient.api.u.pro.attach.auto.full_auto_attach.v1rrZ+uaclient.api.u.pro.attach.magic.initiate.v1rZ)uaclient.api.u.pro.attach.magic.revoke.v1rrZ'uaclient.api.u.pro.attach.magic.wait.v1rr Z5uaclient.api.u.pro.security.status.reboot_required.v1r!rWr"r#Zuaclient.data_typesr$r%Zuaclient.defaultsr&Zuaclient.entitlementsr'r(r)Z(uaclient.entitlements.entitlement_statusr*r+r,r-Zuaclient.filesr.r/Zuaclient.files.noticesr0Zuaclient.jobs.update_messagingr1r2Zuaclient.logr3Z
uaclient.yamlr4r5r�r�r�rKZSTATUS_HEADER_TMPLr�r�r�Z	BLUE_INFOr�Zget_event_loggerr�ArgumentParserr:r~r�r�r�r�r�r�r�rrr�r�r�r�r�r�r�r�r�r�r�rdr�rrrrr	rrr!r�r�r�r`rirurMrxrFrvr�r�r�r�r�r�rr�r�rr�r�r�r�r�rGr�r�r�r�r�r�rnrLrErErErF�<module>s4
�
���
[


 29#'/$P�
 )
}
/)E,!D
}


�
&L)