
"T`                 @   s  d  Z  d d l Z d d l m Z d d l Z d d l Z d d l m Z m Z d d l	 m
 Z
 m Z d d l m Z d d l m Z m Z m Z d d l m Z d	 Z e j e  Z d d
 d  Z d d   Z d d   Z d d   Z e d k r e   d S)aT  Query standardized instance metadata provided to machine, returning a JSON
structure.

Some instance-data values may be binary on some platforms, such as userdata and
vendordata. Attempt to decompress and decode UTF-8 any binary values.

Any binary values in the instance metadata will be base64-encoded and prefixed
with "ci-b64:" in the output. userdata and, where applicable, vendordata may
be provided to the machine gzip-compressed (and therefore as binary data).
query will attempt to decompress these to a string before emitting the JSON
output; if this fails, they are treated as binary.
    N)EACCES)convert_jinja_instance_datarender_jinja_payload)addLogHandlerCLIread_cfg_paths)log)INSTANCE_JSON_FILEINSTANCE_JSON_SENSITIVE_FILEREDACT_SENSITIVE_VALUE)utilZqueryc             C   s'  |  s t  j d t d t  }  |  j d d d d d d d	 d
 |  j d d d t d	 d t |  j d d d d d d d	 d |  j d d d t d	 d |  j d d d t d	 d |  j d d t d d d	 d |  j d d d d d d d d d	 d  |  j d! d" d t d d# d	 d$ |  S)%a#  Build or extend an arg parser for query utility.

    @param parser: Optional existing ArgumentParser instance representing the
        query subcommand which will be extended to support the args of
        this utility.

    @returns: ArgumentParser with proper argument configuration.
    progZdescriptionz-dz--debugaction
store_truedefaultFhelpz+Add verbose messages during template renderz-iz--instance-datatypez>Path to instance-data.json file. Default is /run/cloud-init/%sz-lz--list-keyszBList query keys available at the provided instance-data <varname>.z-uz--user-datazHPath to user-data file. Default is /var/lib/cloud/instance/user-data.txtz-vz--vendor-datazLPath to vendor-data file. Default is /var/lib/cloud/instance/vendor-data.txtvarnamenargs?zA dot-delimited specific variable to query from instance-data. For example: v1.local_hostname. If the value is not JSON serializable, it will be base64-encoded and will contain the prefix "ci-b64:". z-az--alldestdump_allz Dump all available instance-dataz-fz--formatformatzOptionally specify a custom output format string. Any instance-data variable can be specified between double-curly braces. For example -f "{{ v2.cloud_name }}")argparseArgumentParserNAME__doc__add_argumentstrr   )parser r   5/usr/lib/python3/dist-packages/cloudinit/cmd/query.py
get_parser!   s:    		r!   c             C   sX   t  j |  d d } y | j d  SWn+ t k
 rS t  j | d d d d SYn Xd S)zAttempt to return a string of user-data from ud_file_path

    Attempt to decode or decompress if needed.
    If unable to decode the content, raw bytes will be returned.

    @returns: String of uncompressed userdata if possible, otherwise bytes.
    decodeFzutf-8quietTN)r   	load_filer"   UnicodeDecodeErrorZdecomp_gzip)Zud_file_pathZbdatar   r   r    load_userdataQ   s
    r&   c             C   s  d } t  t | j r t j n t j  t | j | j | j	 | j
 g  sj t j d  t   j   d St j   } t | j | j | j g  s t   } | j r | j } ny t j j | j t  } | d k r%t j j | j t  } t j j |  r	| } q+t j d | |  | } n | } | j r@| j } n t j j | j d  } | j rm| j } n t j j | j d  } y t j |  }	 Wna t t  f k
 r}
 z; |
 j! t" k rt j d |  n t j d	 |  d SWYd d }
 ~
 Xn Xt j# |	  } | d k rBd
 t$ | f | d <d
 t$ | f | d <n  t% |  | d <t% |  | d <| j	 rd j	 d | j	  } t& d | d d d | d | j rd n d  } | rt' |  d Sd St( |  } | j r~y+ x$ | j j) d  D] } | | } qWWn) t* k
 r3t j d | j  d SYn X| j rt+ | t,  s`t j d |  d Sd j t- | j.     } n$ | j rd j t- | j.     } t+ | t/  st j0 |  } t' |  d S)z3Handle calls to 'cloud-init query' as a subcommand.NzDExpected one of the options: --all, --format, --list-keys or varname   r   z4Missing root-readable %s. Using redacted %s instead.zuser-data.txtzvendor-data.txtz$No read permission on '%s'. Try sudozMissing instance-data file: %sz<%s> file:%sZuserdataZ
vendordataz## template: jinja
{fmt}ZfmtpayloadZ
payload_fnzquery commandlineinstance_datadebugTF.zUndefined instance-data key %sz+--list-keys provided but '%s' is not a dict
)1r   LOGr*   r   DEBUGZWARNINGanyZ	list_keysr   r   r   errorr!   Z
print_helposgetuidallr)   Z	user_dataZvendor_datar   pathjoinZrun_dirr   r	   existsZwarningZinstance_linkr   r$   IOErrorOSErrorerrnor   Z	load_jsonr
   r&   r   printr   splitKeyError
isinstancedictsortedkeysr   Z
json_dumps)nameargspathsZuidZinstance_data_fnZredacted_data_fnZsensitive_data_fnZuser_data_fnZvendor_data_fnZinstance_jsoner)   r(   Zrendered_payloadZresponsevarr   r   r    handle_args`   s    "$				
				
				
rF   c              C   s)   t    }  t j t t |  j     d S)z,Tool to query specific instance-data values.N)r!   sysexitrF   r   
parse_args)r   r   r   r    main   s    	rJ   __main__)r   r   r9   r   r1   rG   Z!cloudinit.handlers.jinja_templater   r   Zcloudinit.cmd.develr   r   Z	cloudinitr   Zcloudinit.sourcesr   r	   r
   r   r   Z	getLoggerr-   r!   r&   rF   rJ   __name__r   r   r   r    <module>   s"   0Z