o Hcf5@sXddlZddlZddlZddlZddlZddlZddlZddlmZm Z ddl m Z m Z m Z mZmZmZmZmZddl mZddl mZmZddl mZddl mZmZmZddlmZdd lmZm Z m!Z!m"Z"dd l#m$Z$m%Z%m&Z&m'Z'e(Z)e*e+e,Z-d Z.d Z/d e j0dej1dejfddZ2 d:d e j0deej3dej1dejde4f ddZ5 d:d e j0de6de4de4ddf ddZ7 d;d e j0de jddfddZ8dddd ddd!d e j0d"e6d#e4d$e4d%e4d&e6de4d'e ee6fd(d)Z9ddd*d e j0d+e e6d,e4fd-d.Zd/e6ddfd0d1Z: ddS)=N)ListOptional)apicloudsconfigcontract entitlements event_logger exceptions livepatch)log)messagessecret_manager)status)systemtimerutil)AutoAttachCloudInstance)APPARMOR_PROFILESCLOUD_BUILD_INFODEFAULT_CONFIG_FILEDEFAULT_LOG_PREFIX)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_messagesrr)uaclient.timer.update_messagingr!rwriter ua_statusrupdate_activity_token)rrrr!r(2/usr/lib/python3/dist-packages/uaclient/actions.py_handle_partial_attach8s   r*Fservices_to_be_enabledsilentc CsHd}g}g}z)|D]$}t||jdd|j|d\} } || M}| s&||jq tj|jdq WnJtjyJ} zt|jt |||| d} ~ wtj y[||jd}Ynt yy} zd}||j|| WYd} ~ nd} ~ ww|st |||t ||rtj ddt||Ddtjdd|DddS) NT)rname assume_yes allow_betavariantr,)serviceFcSs,g|]\}}|tjjt|tdfqS)) error_msglog_path)r UNEXPECTED_ERRORformatstrpro_logget_user_or_root_log_file_path).0r- exceptionr(r(r) ssz,_enable_default_services..)failed_servicescSsg|]}|tjfqSr()r !E_ATTACH_FAILURE_DEFAULT_SERVICES)r9r-r(r(r)r;s)enable_entitlement_by_namer-r0appendeventservice_processedr ConnectivityErrorservice_failedr*UbuntuProError Exceptionservices_failedAttachFailureUnknownErrorzipAttachFailureDefaultServices) rr+rrr,retr<unexpected_errorsenable_by_default_serviceent_retreasonexcer(r(r)_enable_default_servicesEsb       rQtoken allow_enablereturnc Csddlm}ddlm}tj|t|}t j j t j j d}|j ||d}|j|z||WntjyG} z|j| d} ~ wwtj|didt|} t| |rrt||jj} t|| |||d tt|d ||tdS) 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 )tz)contract_token attachment_dtNmachineTokenInfo machineId)rr+rrr,r")uaclient.entitlementsrUr$r!rsecrets add_secretrUAContractClientdatetimenowtimezoneutcadd_contract_machinemachine_token_filer%r %EntitlementsAPTDirectivesAreNotUniquedeleterget_machine_id cache_cleargetrget_enabled_by_default_servicesrrQrrrstart) rrRrSr,rUr!rrnew_machine_tokenrP machine_idr+r(r(r)attach_with_tokensF           rnTcloudcCs0t|}|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. )instance contractToken)rRrSN)rr^%get_contract_token_for_cloud_instancern)rrorSr tokenResponserRr(r(r) auto_attachs rt)r.r/ access_onlyr0r, extra_argsr-r.r/rvr0rwc Csvtj|||d}|||||||d} |sttjj| jd| t \} } | r7|s7ttj 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-r0)r.r/ called_namervrw)title) rentitlement_factoryr@infor ENABLING_TMPLr5ryenablerProgressWrapper ENABLED_TMPL) rr-r.r/rvr0r,rwent_cls entitlementrMrNr(r(r)r>s" r>)simulate_with_tokenshow_allrrcCs:|rtj|||d\}}||fStj||d}d}||fS)z6 Construct the current Pro status dictionary. )rrRrrrr)r&simulate_statusr)rrrrrJr(r(r)rs   rfilenamec Csgd}d}d}z t|\}}Wn'tjy8}ztdt|td|t|WYd}~dSd}~ww|r[g}| dD] }t ||rO| |qBt|d |dSdS)z Helper which gets ubuntu_pro apparmor logs from the kernel from the last day and writes them to the specified filename. ) journalctlz-bz-kz--since=1 day agoz7apparmor=\".*(profile=\"ubuntu_pro_|name=\"ubuntu_pro_)Nz!Failed to collect kernel logs: %s{}-error )rsubpr ProcessExecutionErrorLOGwarningr6 write_filer5splitresearchr?join)rcmd apparmor_re kernel_logs_rP apparmor_logs kernel_liner(r(r)_write_apparmor_logs_to_files$$  r return_codesc Csjz tj||d\}}Wntjy,}ztd|t|WYd}~dSd}~wwt||dS)zCHelper which runs a command and writes output or error to filename.)rcsrN)rrrr rrr5r6)rrroutrrPr(r(r)_write_command_output_to_file/s$rcs,jptjtjjtgfddtjDS)Nc3s(|]}t|tjjr|jVqdSN) issubclassrrepoRepoEntitlement repo_file)r9rr#r(r) Bs  z#_get_state_files..) cfg_pathrlog_filerua_filepathrrENTITLEMENT_CLASSESr#r(r#r)_get_state_files;s r output_dirc Cstdd|tdtjd|tdd|tdd|td d d d tDd |tD]}td|d||ddgdq9t|dd\}}td|t j |t j dt }td|t |t|}t rtdtntg}t|D]7\}} zt t| } ttj|d|| Wqty} ztd| t| WYd} ~ qd} ~ ww|ttdD]K} tj| rzt| } Wnty} ztd| t| WYd} ~ qd} ~ wwt | } t r t| | ttj|tj | | qt!d|t"D]1} tj| rRz t#$| |Wq"tyQ} ztd| t| WYd} ~ q"d} ~ wwq"dS)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|vrd|qS)z.servicez-u {})r5)r9sr(r(r)r;esz collect_logs..z{}/pro-journal.txtzsystemctl status {}z {}/{}.txtr)rFrz{}/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)%rr5r LIVEPATCH_CMDr UA_SERVICESrrrjsondumpsrDatetimeAwareJSONEncoderget_pro_environmentrwe_are_currently_rootr7get_all_user_log_filesUSER_LOG_COLLECTED_LIMITget_user_log_file enumerateredact_sensitive_logs load_fileosrrErrr6globrisfilebasenamerrshutilcopy) rrr1 pro_statusrenv_vars state_filesuser_log_files log_file_idxrcontentrPfr(r(r) collect_logsJs          r)F)Tr)?r_rrloggingrrrtypingrruaclientrrrrrr r r r r7r rrr&rrruaclient.cloudsruaclient.defaultsrrrruaclient.files.state_filesrrrrget_event_loggerr@ getLoggerreplace_top_level_logger_name__name__rrrUAConfigr^r*EnableByDefaultServiceboolrQr6rnrtr>rintrrrr(r(r(r)s(      H ;  +