
    f%E                        U d 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 ddl	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 dZdgZ eddg      Zddd ed      e edez         ed       ed       ed       ed       ed       ed      gedg ee      z   dZeed<    ee      Z  ej<                  e      Z dZ!dZ"dZ#d e$fd!Z%d"e$fd#Z&d0d"efd$Z'd0d%Z(d&efd'Z)d e$d(e*fd)Z+d e$fd*Z,d e$fd+Z-d,e.d-ed&ed.ed(df
d/Z/y)1z1ubuntu_pro: Configure Ubuntu Pro support services    N)dedent)AnyList)urlparse)subputil)Cloud)Config)
MetaSchemaget_meta_doc)PER_INSTANCEzhttps://ubuntu.com/proubuntuzubuntu-advantageubuntu_advantagecc_ubuntu_proz
Ubuntu Proz%Configure Ubuntu Pro support servicesa<          Attach machine to an existing Ubuntu Pro support contract and
        enable or disable support services such as Livepatch, ESM,
        FIPS and FIPS Updates. When attaching a machine to Ubuntu Pro,
        one can also specify services to enable. When the 'enable'
        list is present, only named services will be activated. Whereas
        if the 'enable' list is not present, the contract's default
        services will be enabled.

        On Pro instances, when ``ubuntu_pro`` config is provided to
        cloud-init, Pro's auto-attach feature will be disabled and cloud-init
        will perform the Pro auto-attach ignoring the ``token`` key.
        The ``enable`` and ``enable_beta`` values will strictly determine what
        services will be enabled, ignoring contract defaults.

        Note that when enabling FIPS or FIPS updates you will need to schedule
        a reboot to ensure the machine is running the FIPS-compliant kernel.
        See `Power State Change`_ for information on how to configure
        cloud-init to perform this reboot.
        z        # Attach the machine to an Ubuntu Pro support contract with a
        # Pro contract token obtained from %s.
        ubuntu_pro:
          token: <ubuntu_pro_token>
    a          # Attach the machine to an Ubuntu Pro support contract enabling
        # only fips and esm services. Services will only be enabled if
        # the environment supports said service. Otherwise warnings will
        # be logged for incompatible services specified.
        ubuntu_pro:
          token: <ubuntu_pro_token>
          enable:
          - fips
          - esm
    a0          # Attach the machine to an Ubuntu Pro support contract and enable
        # the FIPS service.  Perform a reboot once cloud-init has
        # completed.
        power_state:
          mode: reboot
        ubuntu_pro:
          token: <ubuntu_pro_token>
          enable:
          - fips
        ac          # Set a http(s) proxy before attaching the machine to an
        # Ubuntu Pro support contract and enabling the FIPS service.
        ubuntu_pro:
          token: <ubuntu_pro_token>
          config:
            http_proxy: 'http://some-proxy:8088'
            https_proxy: 'https://some-proxy:8088'
            global_apt_https_proxy: 'https://some-global-apt-proxy:8088/'
            global_apt_http_proxy: 'http://some-global-apt-proxy:8088/'
            ua_apt_http_proxy: 'http://10.0.10.10:3128'
            ua_apt_https_proxy: 'https://10.0.10.10:3128'
          enable:
          - fips
        z        # On Ubuntu PRO instances, auto-attach but enable no PRO services.
        ubuntu_pro:
          enable: []
          enable_beta: []
        z        # Enable esm and beta realtime-kernel services in Ubuntu Pro instances.
        ubuntu_pro:
          enable:
          - esm
          enable_beta:
          - realtime-kernel
        z        # Disable auto-attach in Ubuntu Pro instances.
        ubuntu_pro:
          features:
            disable_auto_attach: True
        
ubuntu_pro)idnametitledescriptiondistrosexamples	frequencyactivate_by_schema_keysmetaREDACTEDzUUnable to determine if this is an Ubuntu Pro instance. Fallback to normal Pro attach.)
http_proxyhttps_proxyglobal_apt_http_proxyglobal_apt_https_proxyua_apt_http_proxyua_apt_https_proxypro_sectionc                 L   d| vry | d   }t        |t              s8dt        |      j                   }t        j                  |       t        |      d|vry |d   }t        |t              s8dt        |      j                   }t        j                  |       t        |      y )Nfeaturesz.'ubuntu_pro.features' should be a dict, not a disable_auto_attachzB'ubuntu_pro.features.disable_auto_attach' should be a bool, not a )
isinstancedicttype__name__LOGerrorRuntimeErrorbool)r"   r$   msgr%   s       @/usr/lib/python3/dist-packages/cloudinit/config/cc_ubuntu_pro.pyvalidate_schema_featuresr0      s    $ :&Hh%X''(* 	 			#3 H,"#89)40/099:< 	 			#3 1    
pro_configc                    g }t        | j                               D ]U  \  }}|t        vrt        j	                  d|       %|(	 t        |      }|j                  dvr|j                  d|        W |r)t        dj                  dj                  |                  y# t        t        f$ r |j                  d|        Y w xY w)a  Validate user-provided ua:config option values.

    This function supplements flexible jsonschema validation with specific
    value checks to aid in triage of invalid user-provided configuration.

    Note: It does not log/raise config values as they could be urls containing
    sensitive auth info.

    @param pro_config: Dictionary of config value under 'ubuntu_pro'.

    @raises: ValueError describing invalid values provided.
    z4Not validating unknown ubuntu_pro.config.%s propertyN)httphttpsz-Expected URL scheme http/https for ua:config:zExpected a URL for ua:config:z$Invalid ubuntu_pro configuration:
{}
)sorteditemsKNOWN_PRO_CONFIG_PROPSr*   warningr   schemeappendAttributeError
ValueErrorformatjoin)r2   errorskeyvalue
parsed_urls        r/   supplemental_schema_validationrE      s     FZ--/0 A
U,,KKF ]	A!%J  (99CC5IA& 3::499V;LM
 	
  
+ 	AMM9#?@	As   -B  #CCc                 Z   | y t        | t              s"t        dt        |       j                   d      t        |        g }t        | j                               D ]  \  }}d }i }|t        j                  d|       ddd|g}nd| d}t        j                  d|       t        j                  d	|      r| d
t        j                  |       }n| d
| }ddd|g}d|d d |gz   i}	 t        j                  |fi |  |rQ|D ]  \  }
}t        j'                  d|
|        t        dj)                  dj+                  d |D                          y # t        j                  $ rA}t        |      }	||	j!                  |t"              }	|j%                  ||	f       Y d }~Id }~ww xY w)Nz+ubuntu_pro: config should be a dict, not a z%; skipping enabling config parameterszDisabling Pro config for %sproconfigunsetz	=REDACTEDzEnabling Pro config %sz\s=set	logstringz#Failure enabling/disabling "%s":
%sz3Failure enabling/disabling Ubuntu Pro config(s): {}, c              3   D   K   | ]  \  }}d j                  |        yw)z"{}"N)r?   ).0param_s      r/   	<genexpr>z!set_pro_config.<locals>.<genexpr>  s     M85!&--.Ms    )r&   r'   r,   r(   r)   rE   r7   r8   r*   debugresearchescaper   ProcessExecutionErrorstrreplacer   r<   r:   r?   r@   )r2   enable_errorsrB   rC   redacted_key_valuesubp_kwargs
config_cmd	key_valueeerr_msgrQ   r+   s               r/   set_pro_configrb      s   j$'z"++, -33
 	

 #:.MZ--/0 1
U!=II3S97C8J$'5	!2II.0BCyy&"e1RYYu%5$67	"e1UG,	5)<J&
3B;M:N(NOK	1IIj0K0!1, ) 	NLE5KK>uM	NAHH		M}MM
 	
  )) 	1!fG!-!//%:  #w00		1s   *EF*)6F%%F*c                 0   |g }ndt        |t              rt        j                  d       |g}n;t        |t              s+t        j                  dt        |      j                         g }|rddd| g}ndd| g}|dd t        gz   }t        j                  dd	j                  |             	 t        j                  |d
dh|       |syg d|z   }	 t        j                  |dd
dh      \  }}		 t!        j"                  |      }
g }|
j'                  dg       D ]5  }|d   dk(  rt        j                  d|d          %|j)                  |       7 |r~g }|D ]Z  }|j'                  d      }||j)                  |       d| d|d    }nd|d    d|d    }t        j                  t        |       \ t        ddj                  |      z         y# t        j                  $ rO}t        |      j                  | t              }d| }t        j                  t        |       t        |      |d}~ww xY w# t        j                  $ r#}t        ddj                  |      z         |d}~ww xY w# t         j$                  $ r}t        d|       |d}~ww xY w) z<Call ua commandline client to attach and/or enable services.NzNubuntu_pro: enable should be a list, not a string; treating as a single enablezIubuntu_pro: enable should be a list, not a %s; skipping enabling servicesrG   attachz--no-auto-enablerM   zAttaching to Ubuntu Pro. %s r      )rcsrL   zFailure attaching Ubuntu Pro:
)rG   enablez--assume-yesz--formatjsonT   )capturerg   z!Error while enabling service(s): rN   zPro response was not json: rA   message_codezservice-already-enabledzService `%s` already enabled.servicezFailure enabling `z`: messagezFailure of type `r(   z(Failure enabling Ubuntu Pro service(s): )r&   rY   r*   r:   listr(   r)   r   rT   r@   r   rX   rZ   r   logexcr,   ri   loadsJSONDecodeErrorgetr<   )tokenrh   
attach_cmdredacted_cmdr`   errr.   cmdenable_stdoutrR   enable_respr[   error_servicesrm   s                 r/   configure_pror|     s   ~	FC	 5	
 %0L!!	

  X'95A
Xu-
cr?hZ/LII+SXXl-CD'		*1a&LA 
?&
HC99S$QFCqjj/< !#Mx, "~";;II5s9~FS!	" $&  	"Cggi(G"%%g.*7)3s9~6FG)#f+c#i.9IJKKS!	" 6ii'(
 	
 o %% '!fnnUH-/u5C3Q&	' %% /$))F2CC
	  )-9
	sI   +G H5 .I. H2#A
H--H25I+I&&I+.JJJcloudc                 @   t        j                  d      ry	 | j                  j                          	 | j                  j                  dg       y# t        $ r t        j                  t        d        w xY w# t        $ r t        j                  t        d        w xY w)z.Install ubuntu-advantage-tools if not present.rG   NzPackage update failedzubuntu-advantage-toolsz(Failed to install ubuntu-advantage-tools)	r   whichdistroupdate_package_sources	Exceptionr   rp   r*   install_packages)r}   s    r/   maybe_install_ua_toolsr   k  s    zz%++-%%'?&@A	  C01
  CCDs   A A8 %A58%Breturnc                 ^   t        | j                  di       j                  dd            }|ryddlm} ddlm} 	 t        j                  t        j                  d|      }|j
                  S # |$ r9}t        j                  d	|       t        j                  t               Y d }~yd }~ww xY w)
Nr$   r%   Fr   )UserFacingError)should_auto_attachz6Checking if the instance can be attached to Ubuntu Pro)logfuncr.   funcz%Error during `should_auto_attach`: %s)r-   rs   uaclient.api.exceptionsr   4uaclient.api.u.pro.attach.auto.should_auto_attach.v1r   r   log_timer*   rT   r:   ERROR_MSG_SHOULD_AUTO_ATTACH)r"   r%   r   r   resultexs         r/   _should_auto_attachr   {  s    
B'++,A5I  8	IIH#
 $$$	  		92>01s   &A. .B,3/B''B,c                    | j                  d      }|s"d}t        j                  |       t        |      | j                  d      }|r%t        j	                  ddj                  |             t        || j                  d             y )Nrt   z8`ubuntu_pro.token` required in non-Pro Ubuntu instances.enable_betaz<Ignoring `ubuntu_pro.enable_beta` services in Pro attach: %srN   rh   )rt   rh   )rs   r*   r+   r,   rT   r@   r|   )r"   rt   r.   r   s       r/   _attachr     so    OOG$EH		#3//-0K		JIIk"	
 kooh&?@r1   c                    ddl m}m} ddlm}m} | j                  d      }| j                  d      } |||      }	 t        j                  t        j                  d|d|i	       y # |$ r ||t        j                  d
       Y y Y y |$ r5}d|j                   }	t        j                  |	       t        |	      |d }~ww xY w)Nr   )AlreadyAttachedErrorr   )FullAutoAttachOptionsfull_auto_attachrh   r   )rh   r   zAttaching to Ubuntu Prooptions)r   r.   r   kwargszThe instance is already attached to Pro. Leaving enabled services untouched. Ignoring config directives ubuntu_pro: enable and enable_betaz!Error during `full_auto_attach`: )r   r   r   2uaclient.api.u.pro.attach.auto.full_auto_attach.v1r   r   rs   r   r   r*   rT   r:   r.   r+   r,   )
r"   r   r   r   r   rh   r   r   r   r.   s
             r/   _auto_attachr     s     N __X&F//-0K#G(II)!w'		
   "f&8KK6 '9  (1"&&:		#3R'(s   )A( (C
C0B>>Cr   cfgargsc                 F   d }t        t        j                  |            }|rXt        |      dkD  rt	        ddj                  |      z        t        j                  ddj                  |             ||d      }d|v r |rt        j                  d|d          |d   }|t        j                  d|        y t        |t              s8d	t        |      j                   }t        j                  |       t	        |      d
|v r"d}t        j                  |       t	        |      t        |       t        |j!                  d             t#        |       t        j                  d       t%        |      rt'        |       y |j)                         dhk  st+        |       y y )Nrj   zLUnable to configure Ubuntu Pro. Multiple deprecated config keys provided: %srN   z^Deprecated configuration key(s) provided: %s. Expected "ubuntu_pro"; will attempt to continue.r   r   z;Ignoring deprecated key %s and preferring ubuntu_pro configz=Skipping module named %s, no 'ubuntu_pro' configuration foundz%'ubuntu_pro' should be a dict, not a commandszPDeprecated configuration "ubuntu-advantage: commands" provided. Expected "token"rH   zETo discover more log info, please check /var/log/ubuntu-advantage.logr$   )ro   DEPRECATED_KEYSintersectionlenr,   r@   r*   r:   rT   r&   r'   r(   r)   r+   r   rb   rs   r0   r   r   keysr   )r   r   r}   r   r"   
deprecatedr.   s          r/   handler     s   Ko22378Jz?Q%'+yy'<=  	@IIj!	

 *Q-(sKKM1 ,'		K	
 	T*[!**+- 	 			#3[   	 			#35!;??8,- [)IIO ;'[! J</ 0r1   )N)0__doc__ri   loggingrU   textwrapr   typingr   r   urllib.parser   	cloudinitr   r   cloudinit.cloudr	   cloudinit.configr
   cloudinit.config.schemar   r   cloudinit.settingsr   PRO_URLr   rK   r   ro   r   __annotations__	getLoggerr)   r*   r   r   r9   r'   r0   rE   rb   r|   r   r-   r   r   r   rY   r    r1   r/   <module>r      s   8   	   !   ! # < +
"*)+=>? 4	,  	
 	
	
 	
	
 		
" 		
 			
 		
OO`  ,~_0EEYmj m^ t
g!&   $  6$
t $
N)
s )
Xa
H%  %T %d %8A A#(d #(LB B6 B% Bt B Br1   