Hcf= ddlZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z m Z m Z mZmZmZddlmZmZddlmZddlmZeZdedefd Zej8eeZGd d ej>Z Gd d ejBZ"dZ# d9de ee fde ee fdede ee ffdZ$dgfdedeedefdZ% d:dede&de&de&fdZ'de ee fdede&fdZ(gdZ)e)fdeedefdZ*d eed!e egdfde&fd"Z+d#edejfd$Z,d%edefd&Z-d'Z.d(Z/d)d*d+d,d-d.Z0d/edefd0Z1d1eedeefd2Z2de&fd3Z3d4ed5edefd6Z4d7eefd8Z5y);Nwraps)AnyCallableDictListOptionalUnion) exceptionsmessages)CONFIG_FIELD_ENVVAR_ALLOWLIST)MessagingOperationsnamereturnc\|dk(ry|jd}d|d<dj|S)z1Replace the name of the root logger from __name__. ubuntupror)splitjoin)rnamess //usr/lib/python3/dist-packages/uaclient/util.pyreplace_top_level_logger_namers0 rz JJsOEE!H 88E?c"eZdZdZfdZxZS)DatetimeAwareJSONEncoderzBA json.JSONEncoder subclass that writes out isoformat'd datetimes.cvt|tjr|jSt||SN) isinstancedatetime isoformatsuperdefault)selfo __class__s rr#z DatetimeAwareJSONEncoder.default"s. a** +;;= wq!!r)__name__ __module__ __qualname____doc__r# __classcell__r&s@rrrsL""rrc2eZdZdZfdZedZxZS)DatetimeAwareJSONDecodera, A JSONDecoder that parses some ISO datetime strings to datetime objects. Important note: the "some" is because we seem to only be able extend Python's json library in a way that lets us convert string values within JSON objects (e.g. '{"lastModified": "2019-07-25T14:35:51"}'). Strings outside of JSON objects (e.g. '"2019-07-25T14:35:51"') will not be passed through our decoder. (N.B. This will override any object_hook specified using arguments to it, or used in load or loads calls that specify this as the cls.) cfd|vr|jdt||d|ji|y)N object_hook)popr"__init__r0)r$argskwargsr&s rr2z!DatetimeAwareJSONDecoder.__init__6s4 F " JJ} % $GD,<,<GGrc|jD]'\}}t|ts t|}|||<)|S#t$r|}YwxYwr)itemsrstrparse_rfc3339_date ValueError)r%keyvalue new_values rr0z$DatetimeAwareJSONDecoder.object_hook;s_'') #JC%%& 2!I ## # "& %I&s = A  A )r'r(r)r*r2 staticmethodr0r+r,s@rr.r.(s" H   rr.cfd}|S)aDecorator to retry on exception for retry_sleeps. @param retry_sleeps: List of sleep lengths to apply between retries. Specifying a list of [0.5, 1] tells subp to retry twice on failure; sleeping half a second before the first retry and 1 second before the second retry. @param exception: The exception class to catch and retry for the provided retry_sleeps. Any other exception types will not be caught by the decorator. c4tfd}|S)Ncj} |i|S#$r[}|s|tjdt|t |t j |jdYd}~nd}~wwxYwm)Nz%s: Retrying %d more times.r)copyLOGdebugr7lentimesleepr1)r3r4sleepse exceptionf retry_sleepss r decoratorz)retry..wrapper..decoratorWsz!&&(F.d-f-- .!II5s1vs6{JJvzz!}-- .sA<AA77A<r)rJrLrIrKs` rwrapperzretry..wrapperVs! q .  .r)rIrKrMs`` rretryrOJs" Nrr orig_dictnew_dictpathci}|jD]\}}|j|t}|s|n|dz|z}t|tr(||vrt ||||}|sP|||<Vt||<`||k7sft jd|t||||<|jD]\}}||vs |||<|S)zddlm}|j}d}dj|dj |Dcgc]}|j c}} |j |tdj}||vr |S|j |Ccc}w)aGInteractive prompt message, returning a valid choice from msg. Expects a structured msg which designates choices with square brackets [] around the characters which indicate a valid choice. Uppercase and lowercase responses are allowed. Loop on invalid choices. :return: Valid response character chosen. r) event_loggerrz{} is not one of: {}z, z> ) uaclientr^get_event_loggerformatrupperinfoinputlower)r[r\r^eventr;choice error_msgs rprompt_choicesris&  ) ) +E E&-- tyy}EV&,,.EFI  3d !!# M !  L  9 FsB assume_yesr#c|ry|stj}t|jj }|dk(r|S|dvryy)a Display a confirmation prompt, returning a bool indicating the response :param msg: String custom prompt text to emit from input call. :param assume_yes: Boolean set True to skip confirmation input and return True. :param default: Boolean to return when user doesn't enter any text This function will only prompt a single time, and defaults to "no" (i.e. it returns False). Tr)yyesF)r PROMPT_YES_NOrdrestrip)r[rjr#r;s rprompt_for_confirmationrpsM $$ #J    $ $ &E {  rconfig path_to_valuec0|}i}|jd}|d}|D]-}||k(rd}t|tr|j||}-yt |}|j dk(ry|j dk(ryt j|d|) aJCheck if value parameter can be translated into a boolean 'True' value. @param config: A config dict representing /etc/ubuntu-advantange/uaclient.conf @param path_to_value: The path from where the value parameter was extracted. @return: A boolean value indicating if the value paramater corresponds to a 'True' boolean value. @raises exceptions.UbuntuProError when the value provide by the path_to_value parameter can not be translated into either a 'False' or 'True' boolean value. rfalseFtrueTzboolean string: true or false)rrexpected_valuer;)rrrVrTr7rer InvalidBooleanConfigValue)rqrrr; default_valuepaths leaf_valuer: value_strs ris_config_value_truer}s EM    $ErJ * #M eT "IIc=1EE IF"  g %22':  r)z(Bearer )[^\']+z(\'attach\', \')[^\']+z(\'machineToken\': \')[^\']+(\'token\': \')[^\']+z((\'X-aws-ec2-metadata-token\': \')[^\']+z*(.*\[PUT\] response.*api/token,.*data: ).*z(https://bearer:)[^\@]+z1(/snap/bin/canonical-livepatch\s+enable\s+)[^\s]+z>(Contract\s+value\s+for\s+'resourceToken'\s+changed\s+to\s+).*z(\'resourceToken\': \')[^\']+z(\'contractToken\': \')[^\']+zF(https://contracts.canonical.com/v1/resources/livepatch\?token=)[^\s]+z(\"identityToken\": \")[^\"]+zT(response:\s+http://metadata/computeMetadata/v1/instance/service-accounts.*data: ).*r~z(\'userCode\': \')[^\']+z(\'magic_token=)[^\']+z(--registration-key=\")[^\"]+z(--registration-key=\')[^\']+z(--registration-key=)[^ ]+z(--registration-key \")[^\"]+z(--registration-key \')[^\']+z(--registration-key )[^\s]+z (-p \")[^\"]+z (-p \')[^\']+z (-p )[^\s]+ redact_regexscF|}|D]}tj|d|}|S)z4Redact known sensitive information from log content.z\g<1>)resub)logr redacted_log redact_regexs rredact_sensitive_logsrs3L%N vvl,> M N rmsg_opsprint_fnch|sy|D]*}t|tr |||\}}|di|r*yy)ahEmit messages to the console for user interaction :param msg_op: A list of strings or tuples. Any string items are printed. Any tuples will contain a callable and a dict of args to pass to the callable. Callables are expected to return True on success and False upon failure. :return: True upon success, False on failure. TFrN)rr7)rrmsg_opfunctorr3s rhandle_message_operationsr sE  fc " V "MGT?T?  rdt_strctjdd|}tjdd|}|jdd}tjdd|}tjj |d S) aT Parse a datestring in rfc3339 format. Originally written for compatibility with golang's time.MarshalJSON function. Also handles output of pythons isoformat datetime method. This drops subseconds. :param dt_str: a date string in rfc3339 format :return: datetime.datetime object of time represented by dt_str z(\d{2}:\d{2}:\d{2})\.\d+z\g<1>z(\d{2}:\d{2}:\d{2})$z\g<1>ZZz+00:00z(-|\+)(\d{2}):(\d{2})$z\g<1>\g<2>\g<3>z%Y-%m-%dT%H:%M:%S%z)rrreplacer strptime)rdt_str_without_subseconds dt_str_with_zdt_str_without_zdt_str_with_pythonish_tzs rr8r8&s(!##Xv!FF,EM%,,S(; "vv!#57G     % % "7 rmessagec~tjj*dtjjjvrx|j dd}|j t j dzd}|j t jdzd}|jddj}|S)z} Verify if the system can output unicode characters and if not, remove those characters from the message string. zUTF-8u—- rasciiignore) sysstdoutencodingrbrr OKGREEN_CHECKFAIL_Xencodedecode)rs rhandle_unicode_charactersr]s # #**--335 5 //(C0 //("8"83">C//(//C"7<..(3::< NrctjjDcic]4\}}|jtvs|j ds|dk(r||6c}}Scc}}w)N UA_FEATURESUA_CONFIG_FILE)osenvironr6rer startswith)kvs rget_pro_environmentrws]JJ$$&  Aq 7795 5 << &  1  s9Acnd}|jD]\}}|j|}t|tr t|trt |||Gt|t rDt|t r4t |r"t|dtr||||| |||<|||<y)aMerge the contents of overlay dict into base_dict not only on top-level keys, but on all on the depths of the overlay_dict object. For example, using these values as entries for the function: base_dict = {"a": 1, "b": {"c": 2, "d": 3}} overlay_dict = {"b": {"c": 10}} Should update base_dict into: {"a": 1, "b": {"c": 10, "d": 3}} @param base_dict: The dict to be updated @param overlay_dict: The dict with information to be added into base_dict cdddd}g}|j|}|D]]}d}t|D]7\}} | j||j|k(s*t| |d}9|rM|j|_|j |y)Nrtypeselector)availableResourcesresourceEntitlements overridesFT)rT enumeratedepth_first_merge_overlay_dictappendextend) base_valuesoverlay_valuesr:merge_id_key_mapvalues_to_appendid_key overlay_value was_replacedbase_value_idx base_values rupdate_dict_listz8depth_first_merge_overlay_dict..update_dict_lists"($*#  !%%c*+ 7M L.7 .D (* >>&)]->->v-FF2:}M#'L (   '' 6 7 +,rr)r:N)r6rTrrVrlistrD) base_dict overlay_dictrr:r;rs rrrs -(#((* # U]]3' j$ 'Jud,C *9S>5 A  D )j.E::jmT#B 3C@E"' #"IcN #ramd64i386ppc64elarm64armhf)x86_64i686ppc64leaarch64armv7larchcN|j}tj||Sr)re ARCH_ALIASESrT)r arch_lowers rstandardize_arch_namers J   J 33rarchesct}|D]}|jt|tt |Sr)setaddrsortedr)rdeduplicated_archesrs rdeduplicate_archesrs>%= 5d ;<= $*+ ,,rc0tjdk(S)Nr)rgetuidrNrrwe_are_currently_rootrs 99;! rfilename new_extensioncVtjj|\}}|dz|zS)Nr)rrRsplitext)rrr _extensions rset_filename_extensionrs*ww''1D* #: %%r package_listc zdjtjdj|ddddddzS)N rPFz )widthbreak_long_wordsbreak_on_hyphensinitial_indentsubsequent_indent)rtextwrapwrap)rs rcreate_package_list_strrsF MM&!&!&#"&      r)r)rFF)6r jsonloggingrrrrrE functoolsrtypingrrrrr r r_r r uaclient.defaultsr uaclient.typesrobjectrUr7r getLoggerr'rB JSONEncoderr JSONDecoderr.rOrWriboolrpr}REDACT_SENSITIVE_LOGSrrr8rrrrrrrrrrNrrrsQ   ==);.h g5h?@"t//"t//DBFHCH~)-c3h?B #s(^<!RcC6>C #6: 4$ c3h$ $ $ N@%:S  ) *ud{# 44s4x'8'84nss41#j   444 -tCy-T#Y-t&S&&& s)r