U Pf8 @sddlZddlZddlZddlZddlZddlZddlZddlmZm Z ddl m Z m Z m Z mZmZmZmZmZddl mZddl mZmZddl mZddl mZmZmZddlmZmZmZm Z dd l!m"Z"m#Z#dd l$m%Z%m&Z&m'Z'm(Z(e)Z*e+e,e-Z.d Z/d Z0e j1ej2ejd ddZ3d0e j1eej4ej2eje5dddZ6d1e j1e7e5e5ddddZ8d2e j1e j9ddddZ:ddddde j1e7e5e7e5e ee7dddZ;ddd e j1e e7e5d!d"d#Ze7dd$d%d&Ze j1d*d+d,Z?e j1e7d-d.d/Z@dS)4N)ListOptional)apicloudsconfigcontract entitlements event_logger exceptions livepatch)log)messagessecret_manager)status)systemtimerutil)APPARMOR_PROFILESCLOUD_BUILD_INFODEFAULT_CONFIG_FILEDEFAULT_LOG_PREFIX) machine_tokennotices)AttachmentDataattachment_data_filemachine_id_filetimer_jobs_state_file)zapt-news.servicezesm-cache.servicezua-timer.servicezua-timer.timerzua-auto-attach.pathzua-auto-attach.servicezua-reboot-cmds.servicezubuntu-advantage.service )cfgcontract_client attached_atcCs<ddlm}tt|dtj|d|||dS)Nrupdate_motd_messagesr r)uaclient.timer.update_messagingr"rwriter ua_statusrZupdate_activity_token)rrr r"r(2/usr/lib/python3/dist-packages/uaclient/actions.py_handle_partial_attach8s   r*Frservices_to_be_enabledrr silentc CsTd}g}g}zN|D]D}t||j|j|d\} } || M}| sH||jqtj|jdqWntjk r} z t|jt |||| W5d} ~ XYn`tj k r||jd}Yn<t k r} zd}||j|| W5d} ~ XYnX|sPt |||t ||r:tj ddt||Ddntjdd|DddS) NT)rnamevariantr-)serviceFcSs,g|]$\}}|tjjt|tdfqS))Z error_msgZlog_path)r ZUNEXPECTED_ERRORformatstrpro_logZget_user_or_root_log_file_path).0r.Z exceptionr(r(r) qsz,_enable_default_services..)failed_servicescSsg|]}|tjfqSr()r Z!E_ATTACH_FAILURE_DEFAULT_SERVICES)r4r.r(r(r)r5s)enable_entitlement_by_namer.r/appendeventZservice_processedr ZConnectivityErrorZservice_failedr*ZUbuntuProError ExceptionZservices_failedZAttachFailureUnknownErrorzipZAttachFailureDefaultServices) rr,rr r-retr6Zunexpected_errorsZenable_by_default_serviceent_retreasonexcer(r(r)_enable_default_servicesEsV       rA)rtoken allow_enabler-returnc Csddlm}ddlm}tj|t|}t |}t j j t j jd}|j||d} tj} | didi} tdd | d gD} | d id id d} | rt| }| | krtj|j|jdtjtjj|j|jd|| z ||Wn2tjk r4}z| |W5d}~XYnXtj!"| didt!|}t#||rt $||%}t&|||||dt't(|d||t)*dS)aC Common functionality to take a token and attach via contract backend :raise ConnectivityError: On unexpected connectivity issues to contract server or inability to access identity doc from metadata service. :raise ContractAPIError: On unexpected errors when talking to the contract server. r)+check_entitlement_apt_directives_are_uniquer!)Ztz)Zcontract_tokenZ attachment_dtZmachineTokenInfo contractInfocss*|]"}|ddkr|d|fVqdS)typesupportN)get)r4r@r(r(r) sz$attach_with_token..ZresourceEntitlementsrHZ affordancesZ onlySeriesN)releaseseries_codenameZ machineIdr+r#)+Zuaclient.entitlementsrEr%r"rZsecretsZ add_secretrZget_machine_token_filerUAContractClientdatetimeZnowtimezoneZutcZadd_contract_machinerZget_release_infoZseriesrIdictZget_distro_infor ZAttachFailureRestrictedReleaserKrLraddZNoticeZLIMITED_TO_RELEASEr&Z%EntitlementsAPTDirectivesAreNotUniquedeleteZget_machine_id cache_clearrZget_enabled_by_default_servicesrrArrrstart)rrBrCr-rEr"Zmachine_token_filerr Znew_machine_tokenZcurrent_seriesrFZsupport_resourceZ only_seriesZallowed_releaser@Z machine_idr,r(r(r)attach_with_tokens               rUT)rcloudrDcCs0t|}|j|d}|d}t|||ddS)a\ :raise ConnectivityError: On unexpected connectivity issues to contract server or inability to access identity doc from metadata service. :raise ContractAPIError: On unexpected errors when talking to the contract server. :raise NonAutoAttachImageError: If this cloud type does not have auto-attach support. )instanceZ contractToken)rBrCN)rrMZ%get_contract_token_for_cloud_instancerU)rrVrCrZ tokenResponserBr(r(r) auto_attachs rX) access_onlyr/r- extra_args)rr.rZr/r-r[c Csftj|||||d}|s.ttjj|jd|t \}}|r^|s^ttj j|jd||fS)z Constructs an entitlement based on the name provided. Passes kwargs onto the entitlement constructor. :raise EntitlementNotFoundError: If no entitlement with the given name is found, then raises this error. )rr.r/rZr[)title) rZentitlement_factoryr9infor Z ENABLING_TMPLr1r\enablerZProgressWrapperZ ENABLED_TMPL) rr.rZr/r-r[Z entitlementr=r>r(r(r)r7sr7)simulate_with_tokenshow_all)rr_r`cCs4|rtj|||d\}}ntj||d}d}||fS)z6 Construct the current Pro status dictionary. )rrBr`rr`r)r'Zsimulate_statusr)rr_r`rr<r(r(r)rs  r)filenamerDc Csddddg}d}d}zt|\}}WnJtjk rp}z*tdt|td|t|W5d}~XYnBX|rg}| d D]}t ||r| |qt|d |dS) z Helper which gets ubuntu_pro apparmor logs from the kernel from the last day and writes them to the specified filename. Z journalctlz-bz-kz--since=1 day agoz7apparmor=\".*(profile=\"ubuntu_pro_|name=\"ubuntu_pro_)Nz!Failed to collect kernel logs: %s{}-error )rsubpr ProcessExecutionErrorLOGwarningr2 write_filer1splitresearchr8join)rbcmdZ apparmor_reZ kernel_logs_r@Z apparmor_logsZ kernel_liner(r(r)_write_apparmor_logs_to_file)s (  rp)rb return_codesrDc Csnztj||d\}}Wn:tjk rT}ztd|t|W5d}~XYnXt|d||dS)zCHelper which runs a command and writes output or error to filename.)ZrcsrcNzstdout: {} stderr: {})rrerjr rfrir1r2)rnrbrqouterrr@r(r(r)_write_command_output_to_fileBs( rtr$cs,jptjtjjtffddtjDS)Nc3s&|]}t|tjjr|jVqdS)N) issubclassrZrepoZRepoEntitlementZ repo_file)r4Zentitlement_clsr$r(r)rJWsz#_get_state_files..) Zcfg_pathrlog_filerZua_filepathrrZENTITLEMENT_CLASSESr$r(r$r)_get_state_filesPs rx)r output_dirc Cstdd|tdtjd|tdd|tdd|td d d d tDd |tD]$}td|d||ddgdqrt|dd\}}td|t j |t j dt }td|t |t|}t rtdtntg}t|D]r\}} z0t t| } ttj|d|| Wn6tk r} ztd| t| W5d} ~ XYnXq|ttdD]} tj| rzt| } Wn@tk r} z td| t| WYqW5d} ~ XYnXt | } t r"t| | ttj|tj | | qt!d|t"D]f} tj| rVzt#$| |Wn@tk r} z td| t| WYqVW5d} ~ XYnXqVdS)zG Write all relevant Ubuntu Pro logs to the specified directory zcloud-idz{}/cloud-id.txtz {} statusz{}/livepatch-status.txtzsystemctl list-timers --allz{}/systemd-timers.txtzujournalctl --boot=0 -o short-precise -u cloud-init-local.service -u cloud-init-config.service -u cloud-config.servicez{}/cloud-init-journal.txtzjournalctl -o short-precise {} cSsg|]}d|krd|qS)z.servicez-u {})r1)r4sr(r(r)r5zsz collect_logs..z{}/pro-journal.txtzsystemctl status {}z {}/{}.txtr)rqFraz{}/pro-status.json)clsz{}/environment_vars.jsonNz user{}.logz&Failed to collect user log file: %s %s*zFailed to load file: %s %sz{}/apparmor_logs.txtzFailed to copy file: %s %s)%rtr1r Z LIVEPATCH_CMDrm UA_SERVICESrrrijsondumpsrZDatetimeAwareJSONEncoderZget_pro_environmentrxZwe_are_currently_rootr3Zget_all_user_log_filesUSER_LOG_COLLECTED_LIMITZget_user_log_file enumerateZredact_sensitive_logsZ load_fileosrwr:rgrhr2globrisfilebasenamerprshutilcopy) rryr0Z pro_statusroZenv_varsZ state_filesZuser_log_filesZ log_file_idxrvZcontentr@fr(r(r) collect_logs_s       r)F)F)T)N)ArNrrZloggingrrkrtypingrrZuaclientrrrrrr r r r r3r rrr'rrrZuaclient.defaultsrrrrZuaclient.filesrrZuaclient.files.state_filesrrrrZget_event_loggerr9Z getLoggerZreplace_top_level_logger_name__name__rgrrZUAConfigrMr*ZEnableByDefaultServiceboolrAr2rUZAutoAttachCloudInstancerXr7rpintrtrxrr(r(r(r)s(     F V  %