Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
python3-dmapi / usr / lib / python3 / dist-packages / dmapi / __pycache__ / utils.cpython-35.pyc
Size: Mime:


èáþ\ ±ã@s|dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlZddlmZddlmZddlZddlmZddlmZddlmZddlmZ ddl!Z"dd	l#m$Z$dd
l#m%Z%ddl#m&Z&ddl#m'Z'dd
l#m(Z(ddl#m)Z)ddl*Z*ddl+m,Z,ddl-Z.ddl.m/Z/ddl0m1Z1m2Z2m3Z3m4Z4ddl.m5Z5e&j6dƒZ7e.j8j9Z9e j:e;ƒZ<dZ=ej>dƒZ?dZ@d‘ZAd’ZBd“ZCiaDd"d#„ZEGd$d%„d%eFƒZGGd&d'„d'eGƒZHd(d)„ZId*d+„ZJd,d-„ZKd.d/d0„ZLd”ZMddd4d5„ZNdeMd6d7„ZOd8d9„ZPd:d;„ZQd<d=„ZRd>d?„ZSd@dA„ZTdBdC„ZUdDdE„ZVddFdG„ZWejXdHdI„ƒZYdJdK„ZZejXddLdM„ƒZ[ejXdNdO„ƒZ\ddPdQ„Z]GdRdS„dSeFƒZ^ddTdUdV„Z_dTdWdX„Z`dYdZ„Zad[d\„Zbd]d^„Zcd_d`„ZdGdadb„dbeFƒZeddddcdd„Zfdddedf„Zgdgdh„Zhdidj„Zidkdl„Zjdmdn„Zkdodp„Zldddqdr„Zmdsdt„Znddudv„Zodwdx„Zpdydz„Zqd{d|„Zrd}d~„Zsdd€„Ztddd‚„Zudƒd„„ZvdTd…d†„Zwd‡dˆ„Zxdd‰dŠ„Zyd‹dŒ„ZzddŽ„Z{dd„Z|dS)•zUtilities and helper functions.éN)Ú
exceptions)Úloading)Ú	lockutils)Úprocessutils)Úcontext)Úlog)Úencodeutils)Úexcutils)Úimportutils)Ústrutils)Ú	timeutils)Úunits)Úrange)Ú	exception)Ú_Ú_LEÚ_LIÚ_LW)Ú
safe_utilszosprofiler.profilerzdmapi-Zimage_Úmin_ramÚmin_diskÚdisk_formatÚcontainer_formatÚmappingsÚblock_device_mappingÚimg_mappingsÚimg_block_device_mappingÚimage_idÚ
image_nameÚsizeÚchecksumcCs&tjjrd}n
dtj}|S)NÚsudozsudo dmapi-rootwrap %s)ÚCONFZworkaroundsZdisable_rootwrapÚrootwrap_config)Úcmd©r%ú-/usr/lib/python3/dist-packages/dmapi/utils.pyÚget_root_helperQs	
r'c@s(eZdZdd„Zdd„ZdS)ÚRootwrapProcessHelpercOstƒ|d<tj||ŽS)NÚroot_helper)r'rÚtrycmd)Úselfr$Úkwargsr%r%r&r*Zs
zRootwrapProcessHelper.trycmdcOstƒ|d<tj||ŽS)Nr))r'rÚexecute)r+r$r,r%r%r&r-^s
zRootwrapProcessHelper.executeN)Ú__name__Ú
__module__Ú__qualname__r*r-r%r%r%r&r(Ysr(c@sReZdZiZedƒdd„ƒZdd„Zdd„Zdd	„Zd
S)ÚRootwrapDaemonHelperzdaemon-client-lockcCsay|j|SWnKtk
r\ddlm}|jdd|gƒ}||j|<|SYnXdS)Nr)Úclientr!zdmapi-rootwrap-daemon)Ú_clientsÚKeyErrorZ
oslo_rootwrapr2ZClient)Úclsr#r2Z
new_clientr%r%r&Ú_get_clientfs

z RootwrapDaemonHelper._get_clientcCs|j|ƒ|_dS)N)r6r2)r+r#r%r%r&Ú__init__qszRootwrapDaemonHelper.__init__cOsž|jddƒ}y"|j||Ž\}}d}WnDtjk
rz}z!dtj|ƒ}}d}WYdd}~XnX|r”|r”|r”d}||fS)NÚdiscard_warningsFÚT)Úpopr-rÚProcessExecutionErrorÚsixÚ	text_type)r+Úargsr,r8ÚoutÚerrÚfailedZexnr%r%r&r*ts
zRootwrapDaemonHelper.trycmdcOsødd„|Dƒ}|jdtjƒ}|jddƒ}|jddƒ}|jddƒ}|jdd	ƒ}|jd
dgƒ}d}	t|tƒr­|}	dg}nt|tƒrÅ|g}tjd
j|ƒƒ}
t	j
tdƒd|
d|iƒxò|dkró|d	8}yÛtjƒ}t	j
|tdƒ|
ƒ|jj||ƒ\}}
}tjƒ|}t	j
|dd|
d|d|iƒ|	rè||krètj|
ƒ}
tj|ƒ}tjd|d|
d|d|
ƒ‚|
|fSWqtjk
rï}z×|tjks0|tjkr||r|tdƒ}t	j
||d|jd|jd|jd|jd|jiƒ|s¡t	j
|tdƒ|
ƒ‚n<t	j
|tdƒ|
ƒ|rÝtjtjddƒd ƒWYdd}~XqXqWdS)!NcSsg|]}t|ƒ‘qSr%)Ústr)Ú.0Úcr%r%r&ú
<listcomp>†s	z0RootwrapDaemonHelper.execute.<locals>.<listcomp>ÚloglevelÚ
log_errorsÚ
process_inputÚdelay_on_retryTÚattemptséÚcheck_exit_coderFú zHExecuting RootwrapDaemonHelper.execute cmd=[%(cmd)r] kwargs=[%(kwargs)r]r$r,zRunning cmd (subprocess): %szECMD "%(sanitized_cmd)s" returned: %(return_code)s in %(end_time)0.3fsÚ
sanitized_cmdZreturn_codeÚend_timeÚ	exit_codeÚstdoutÚstderrzS%(desc)r
command: %(cmd)r
exit code: %(code)r
stdout: %(stdout)r
stderr: %(stderr)rÚdescÚcodez%r failed. Not Retrying.z%r failed. Retrying.ééÈgY@)r:ÚloggingÚDEBUGÚ
isinstanceÚboolÚintrZ
mask_passwordÚjoinÚLOGÚinforÚtimerrr2r-rr;ZLOG_ALL_ERRORSZLOG_FINAL_ERRORÚdescriptionr$rPrQrRÚsleepÚrandomÚrandint)r+r$r,rFrGrHrIrJrLZignore_exit_coderNZ
start_timeÚ
returncoder?r@rOÚformatr%r%r&r-sr	
		
					zRootwrapDaemonHelper.executeN)	r.r/r0r3Úsynchronizedr6r7r*r-r%r%r%r&r1cs

r1cOs`d|krP|jdƒrPtjr=ttjƒj||ŽStƒj||ŽStj||ŽS)z3Convenience wrapper around oslo's execute() method.Úrun_as_root)Úgetr"Úuse_rootwrap_daemonr1r#r-r(r)r$r,r%r%r&r-Îs	
r-cOs6dddg}|j|ƒ|j|ƒt||ŽS)z+Convenience wrapper to execute ssh command.Zsshz-oz
BatchMode=yes)ÚappendÚextendr-)Údestr$r,Zssh_cmdr%r%r&Ússh_executeÙs

rmcOsW|jddƒrGtjr4ttjƒj||ŽStƒj||ŽStj||ŽS)z2Convenience wrapper around oslo's trycmd() method.rgF)rhr"rir1r#r*r(r)r>r,r%r%r&r*ás	
r*écs<d‰‡fdd†t|ƒDƒ}d|dj|ƒfS)NZ%01234567890abcdefghijklmnopqrstuvwxyzcsg|]}tjˆƒ‘qSr%)rbÚchoice)rCZ_x)Ú
charactersr%r&rEîs	z generate_uid.<locals>.<listcomp>z%s-%sr9)rr\)ZtopicrÚchoicesr%)rpr&Úgenerate_uidìsrrÚ23456789ÚABCDEFGHJKLMNPQRSTUVWXYZÚabcdefghijkmnopqrstuvwxyzc	Cs7|stj}d}d|krE|jddƒ\}}t|ƒ}|dk	rZ|}ntjƒ}|dkr„ttd	ƒƒ‚|dkr—|dkr¢d}tjd|d|j	d|j
ƒ}||kr3|j
}d|j	kr|d8}d
|j	d}n
|j	d}tjd|d|d|ƒ}|j
}d|j	kri|d8}d
|j	d}n
|j	d}tjd|d|d|ƒ}n–|dkrW|dkrµd}tjddd|d|j
ƒ}||kr/tjddd|d|j
dƒ}tjddd|d|j
dƒ}q-tjddd|d|j
dƒ}nÖ|dkrËtjd|d|jd|j	d|j
ƒ}||kr²|tjddƒ}|tjddƒ}nb|dkr-|j
d
|ddddƒ}||kr|tjddƒ}|tjddƒ}||fS)a§This method gives you the most recently *completed* audit period.

    arguments:
            units: string, one of 'hour', 'day', 'month', 'year'
                    Periods normally begin at the beginning (UTC) of the
                    period unit (So a 'day' period begins at midnight UTC,
                    a 'month' unit on the 1st, a 'year' on Jan, 1)
                    unit string may be appended with an optional offset
                    like so:  'day@18'  This will begin the period at 18:00
                    UTC.  'month@15' starts a monthly period on the 15th,
                    and year@3 begins a yearly one on March 1st.
            before: Give the audit period most recently completed before
                    <timestamp>. Defaults to now.


    returns:  2 tuple of datetimes (begin, end)
              The begin timestamp of this audit period is the same as the
              end of the previous.
    rú@rKNÚmonthÚdayÚyearÚhourz,Time period must be hour, day, month or yearééÚdaysÚminuteÚsecondÚmicrosecondÚhours)zmonthzdayzyearzhour)r"Zinstance_usage_audit_periodÚsplitr[rÚutcnowÚ
ValueErrorrÚdatetimerwryrxÚ	timedeltaÚreplace)ZunitÚbeforeÚoffsetZrightnowÚendryrwÚbeginr%r%r&Úlast_completed_audit_periodùsx				

		

!!		rŒcs¹|dkrtj}tjƒ‰‡fdd†|Dƒ}ˆj|ƒ|d|…}|t|ƒ8}dj|ƒ‰|j‡‡fdd†t|ƒDƒƒˆj|ƒdj|ƒS)aGenerate a random password from the supplied symbol groups.

    At least one symbol from each group will be included. Unpredictable
    results if length is less than the number of symbol groups.

    Believed to be reasonably secure (with a reasonable password length!)

    Ncsg|]}ˆj|ƒ‘qSr%)ro)rCÚs)Úrr%r&rEfs	z%generate_password.<locals>.<listcomp>r9csg|]}ˆjˆƒ‘qSr%)ro)rCZ_i)rŽÚsymbolsr%r&rEps	)	r"Zpassword_lengthrbÚSystemRandomÚshuffleÚlenr\rkr)ÚlengthZsymbolgroupsÚpasswordr%)rŽrr&Úgenerate_passwordUs		
)
r•cCsP|dkst|tjƒr"|St|tjƒsCtj|ƒ}|jdƒS)z³Try to turn a string into utf-8 if possible.

    The original code was copied from the utf8 function in
    http://github.com/facebook/tornado/blob/master/tornado/escape.py

    Nzutf-8)rYr<Úbinary_typer=Úencode)Úvaluer%r%r&Úutf8zs
r™cCsÚyžtj|ƒr|dfS|jdƒdkr_|jdddƒjdƒ\}}||fS|jdƒd	kr~|dfS|jdƒ\}}||fSWn5ttjfk
rÕtjt	dƒ|ƒd
SYnXdS)zôParses the given server_string and returns a tuple of host and port.
    If it's not a combination of host part and port, the port element
    is an empty string. If the input is invalid expression, return a tuple of
    two empty strings.
    r9z]:rKú[ú:zInvalid server_string: %sNéÿÿÿÿrœ)r9r9)
ÚnetaddrZ
valid_ipv6Úfindr‡r‚r„ÚAddrFormatErrorr]Úerrorr)Z
server_strÚaddressÚportr%r%r&Úparse_server_stringŠs
$

r£cCs%tj|ddƒ}t|jƒƒS)NÚversioné)rÚ	IPAddressrBZipv6)r¡Úaddrr%r%r&Úget_shortened_ipv6§sr¨cCs"tj|ddƒ}t|jƒS)Nr¤r¥)rZ	IPNetworkrBZcidr)r¡Únetr%r%r&Úget_shortened_ipv6_cidr¬srªcCsFy$tj|ƒjdkr#d|SWnttjfk
rAYnX|S)zŽTransform ip string to "safe" format.

    Will return ipv4 addresses unchanged, but will nest ipv6 addresses
    inside square brackets.
    r¥z[%s])rr¦r¤Ú	TypeErrorrŸ)Úipr%r%r&Úsafe_ip_format±sr­cCs$|dkr|Sdt|ƒ|fS)zÌReturns remote path in format acceptable for scp/rsync.

    If host is IPv6 address literal, return '[host]:path', otherwise
    'host:path' is returned.

    If host is None, only path is returned.
    Nz%s:%s)r­)ÚhostÚpathr%r%r&Úformat_remote_pathÀsr°cCs|tjs
dStjdƒtjr/tj}ndd„}x:tjD]/}|j	dƒ\}}t
j|ƒ}t|ƒt
j|ƒ}xét|jƒƒD]Õ\}}t|t
jƒrt
jd||fƒ}xFtj||ƒD]2\}	}
t||	|d|||	f|
ƒƒqåWt|t
jƒr›t
jd||fƒ}
ttj|||d||f|
ƒƒq›WqEWdS)aÿDEPRECATED: If the CONF.monkey_patch set as True,
    this function patches a decorator
    for all functions in specified modules.
    You can set decorators for each modules
    using CONF.monkey_patch_modules.
    The format is "Module path:Decorator function".
    Example:
    'dmapi.api.ec2.cloud:dmapi.notifications.notify_decorator'

    Parameters of the decorator is as follows.
    (See dmapi.notifications.notify_decorator)

    name - name of the function
    function - object of the function
    Nz0Monkey patching dmapi is deprecated for removal.cSstj|ƒptj|ƒS)N)ÚinspectÚismethodÚ
isfunction)Úobjr%r%r&Ú	is_methodæszmonkey_patch.<locals>.is_methodr›z%s.%sz%s.%s.%s)r"Úmonkey_patchr]Úwarningr<ÚPY2r±r²Zmonkey_patch_modulesr‚r
Zimport_classÚ
__import__ÚpyclbrZ
readmodule_exÚlistÚitemsrYZClassÚ
getmembersÚsetattrZFunctionÚsysÚmodules)rµZmodule_and_decoratorÚmoduleZdecorator_nameÚ	decoratorZmodule_dataÚkeyr˜ZclzÚmethodÚfuncr%r%r&r¶Ïs*	
	
	!r¶cCs¿dd„}t|tjƒrH|jddƒ}tjrH|jdƒ}||ƒ}tjdd|ƒ}tjdd|ƒ}|jƒ}|j	d	ƒ}|dkr»|d
k	r»||ƒS|S)asReturn a hostname which conforms to RFC-952 and RFC-1123 specs except
       the length of hostname.

       Window, Linux, and Dnsmasq has different limitation:

       Windows: 255 (net_bios limits to 15, but window will truncate it)
       Linux: 64
       Dnsmasq: 63

       Due to dmapi-network will leverage dnsmasq to set hostname, so we chose
       63.

       cSsLt|ƒdkr>tjtdƒd|d|dd…iƒ|dd…S)Né?zJHostname %(hostname)s is longer than 63, truncate it to %(truncated_name)sÚhostnameZtruncated_name)r’r]r·r)Únamer%r%r&Útruncate_hostnamesz,sanitize_hostname.<locals>.truncate_hostnamezlatin-1Úignorez[ _]ú-z[^\w.-]+r9z.-N)
rYr<r=r—ÚPY3ÚdecodeÚreÚsubÚlowerÚstrip)rÇZdefault_namerÉr%r%r&Úsanitize_hostnameÿs	
rÒc
+súdd„‰‡fdd†}‡fdd†}‡fdd†}tƒ}i}xFt|jƒƒD]2\}}||||ƒ||<||||ƒqdWz	d	VWd	xLt|jƒƒD]8\}}	|	|krá|||ƒq¹||||	ƒq¹WXd	S)
a4Temporarily set the attr on a particular object to a given value then
    revert when finished.

    One use of this is to temporarily set the read_deleted flag on a context
    object:

        with temporary_mutation(context, read_deleted="yes"):
            do_something_that_needed_deleted_objects()
    cSst|dƒpt|tƒS)NZhas_key)ÚhasattrrYÚdict)Úthingr%r%r&Úis_dict_like2sz(temporary_mutation.<locals>.is_dict_likecs0ˆ|ƒr|j||ƒSt|||ƒSdS)N)rhÚgetattr)rÕÚattrÚdefault)rÖr%r&rh5sztemporary_mutation.<locals>.getcs-ˆ|ƒr|||<nt|||ƒdS)N)r¾)rÕrØÚval)rÖr%r&Ú	set_value;s
z%temporary_mutation.<locals>.set_valuecs'ˆ|ƒr||=n
t||ƒdS)N)Údelattr)rÕrØ)rÖr%r&ÚdeleteAs
z"temporary_mutation.<locals>.deleteN)Úobjectr»r¼)
r´r,rhrÛrÝZNOT_PRESENTZ
old_valuesrØÚ	new_valueÚ	old_valuer%)rÖr&Útemporary_mutation's		rácCsVdddtjddƒtjddƒtjddƒg}djdd„|DƒƒS)	z!Generate an Ethernet MAC address.éúéé>réÿr›cSsg|]}d|‘qS)z%02xr%)rCÚxr%r%r&rEds	z(generate_mac_address.<locals>.<listcomp>)rbrcr\)Zmacr%r%r&Úgenerate_mac_addressXs
	rçc
cs…|dkrtjƒ}tj|ƒj}||krOtjjj|d|ƒz	dVWd||kr€tjjj|d|ƒXdS)zgTemporarily chown a path.

    :param owner_uid: UID of temporary owner (defaults to current user)
    NÚuid)ÚosÚgetuidÚstatÚst_uidÚdmapiZprivsepr¯Úchown)r¯Z	owner_uidZorig_uidr%r%r&Útemporary_chownks	rïcks”|jƒ}d|kr%tj|d<tj|}z	|VWdytj|ƒWn;tk
rŽ}ztj	t
dƒ|ƒWYdd}~XnXXdS)NÚdirzCould not remove tmpdir: %s)Úcopyr"ÚtempdirÚtempfileÚmkdtempÚshutilÚrmtreeÚOSErrorr]r r)r,ZargdictÚtmpdirÚer%r%r&ròs
	ròccsd|sg}xQ|jƒD]C}||kr|j|ƒxt||ƒD]}|VqHW|VqWdS)z:Walk class hierarchy, yielding most derived classes first.N)Ú__subclasses__rjÚwalk_class_hierarchy)ZclazzZencounteredÚsubclassZsubsubclassr%r%r&rûŽs
	rûc@sIeZdZdZdd„Zdd„Zdd„Zdd	d
„ZdS)ÚUndoManagerziProvides a mechanism to facilitate rolling back a series of actions
    when an exception is raised.
    cCs
g|_dS)N)Ú
undo_stack)r+r%r%r&r7ŸszUndoManager.__init__cCs|jj|ƒdS)N)rþrj)r+Ú	undo_funcr%r%r&Ú	undo_with¢szUndoManager.undo_withcCs%xt|jƒD]
}|ƒqWdS)N)Úreversedrþ)r+rÿr%r%r&Ú	_rollback¥szUndoManager._rollbackNc
Ks8tjƒ%|r#tj|||jƒWdQRXdS)z¦Rollback a series of actions then re-raise the exception.

        .. note:: (sirp) This should only be called within an
                  exception handler.
        N)r	Úsave_and_reraise_exceptionr]rr)r+Úmsgr,r%r%r&Úrollback_and_reraise©s
z UndoManager.rollback_and_reraise)r.r/r0Ú__doc__r7rrrr%r%r%r&rý›s
rýFcCs˜|dkrdg}ndd|g}|dkrC|jdgƒ|rw|dkr^d}nd}|j||gƒ|j|ƒt|d
|ŒdS)zçFormat a file or block device

    :param fs: Filesystem type (examples include 'swap', 'ext3', 'ext4'
               'btrfs', etc.)
    :param path: Path to file or block device to format
    :param label: Volume label to use
    ZswapZmkswapÚmkfsz-tÚext3Úext4Úntfsz-FÚmsdosÚvfatz-nz-LrgN)rr	r
)rr)rkrjr-)Úfsr¯Úlabelrgr>Z	label_optr%r%r&r¶s	
rcCsFi}x9|D]1}|r,|jdƒr,q
|d||d<q
W|S)NZdeletedr˜rÃ)rh)ÚmetadataÚinclude_deletedÚresultÚitemr%r%r&Úmetadata_to_dictÏs
rcCsIg}x<t|jƒƒD](\}}|jtd|d|ƒƒqW|S)NrÃr˜)r»r¼rjrÔ)rrrÃr˜r%r%r&Údict_to_metadataØs rcCs-t|dtƒr|dSt|dƒSdS)Nr)rYrÔr)Úinstancer%r%r&Ú
instance_metaßsrcCsF|jdƒsiSt|dtƒr.|dSt|dddƒSdS)NZsystem_metadatarT)rhrYrÔr)rr%r%r&Úinstance_sys_metaæs
rcs‡fdd†}|S)Ncs(tjˆƒ‡‡fdd†ƒ}|S)Ncs~tj|ƒ}tj|ƒ\}}}}|sN|sNtˆƒt|ƒkrXˆ|ƒStdd|jdˆjiƒ‚dS)Nz^Decorated function %(f_name)s does not have the arguments expected by the decorator %(d_name)sÚf_nameZd_name)rZget_wrapped_functionr±Ú
getargspecÚsetr«r.)ÚfZbase_fÚ	arg_namesÚaÚkwÚ_default)r>Údecr%r&Ú
_decoratoròs$
	zAexpects_func_args.<locals>._decorator_checker.<locals>._decorator)Ú	functoolsÚwraps)r r!)r>)r r&Ú_decorator_checkerñs$z-expects_func_args.<locals>._decorator_checkerr%)r>r$r%)r>r&Úexpects_func_argsðsr%c@s.eZdZdZdd„Zdd„ZdS)ÚExceptionHelperzrClass to wrap another and translate the ClientExceptions raised by its
    function calls to the actual ones.
    cCs
||_dS)N)Ú_target)r+Útargetr%r%r&r7
szExceptionHelper.__init__cs7t|j|ƒ‰tjˆƒ‡fdd†ƒ}|S)NcsPyˆ||ŽSWn8tjk
rK}ztj|jŒWYdd}~XnXdS)N)Ú	messagingZExpectedExceptionr<ÚreraiseÚexc_info)r>r,rù)rÅr%r&Úwrappersz,ExceptionHelper.__getattr__.<locals>.wrapper)r×r'r"r#)r+rÈr,r%)rÅr&Ú__getattr__
s!zExceptionHelper.__getattr__N)r.r/r0rr7r-r%r%r%r&r&sr&cCsët|tjƒsO|dkr-tdƒ}ntdƒ|}tjd|ƒ‚|dkra|}t|ƒ|kr¡tdƒd|d|i}tjd|ƒ‚|rçt|ƒ|krçtdƒd|d	|i}tjd|ƒ‚dS)
zãCheck the length of specified string
    :param value: the value of the string
    :param name: the name of the string
    :param min_length: the min_length of the string
    :param max_length: the max_length of the string
    Nz$The input is not a string or unicodez%s is not a string or unicodeÚmessagez?%(name)s has a minimum character requirement of %(min_length)s.rÈÚ
min_lengthz1%(name)s has more than %(max_length)s characters.Ú
max_length)rYr<Ústring_typesrrÚInvalidInputr’)r˜rÈr/r0rr%r%r&Úcheck_string_lengths		r3cCsaytj||||ƒSWn@tk
r\}z tjdtj|ƒƒ‚WYdd}~XnXdS)aAMake sure that value is a valid integer, potentially within range.

    :param value: value of the integer
    :param name: name of the integer
    :param min_value: min_value of the integer
    :param max_value: max_value of the integer
    :returns: integer
    :raise: InvalidInput If value is not a valid integer
    ÚreasonN)rÚvalidate_integerr„rr2r<r=)r˜rÈZ	min_valueZ	max_valuerùr%r%r&r55s
r5cCsMts
dStjƒ}d}|rId|jd|jƒd|jƒi}|S)NÚhmac_keyZbase_idZ	parent_id)Úprofilerrhr6Zget_base_idZget_id)ZprofZ
trace_infor%r%r&Ú_serialize_profile_infoEs	r8csOtjƒ‰tƒ‰tjˆƒ‡‡‡fdd†ƒ}tj|||ŽS)amPassthrough method for eventlet.spawn.

    This utility exists so that it can be stubbed for testing without
    interfering with the service spawns.

    It will also grab the context from the threadlocal store and add it to
    the store on the new thread.  This allows for continuity in logging the
    context when using this method to spawn a new thread.
    cs<ˆdk	rˆjƒˆr/tr/tjˆˆ||ŽS)N)Úupdate_storer7Úinit)r>r,)Ú_contextrÅÚ
profiler_infor%r&Úcontext_wrapperbs


zspawn.<locals>.context_wrapper)Úcommon_contextÚget_currentr8r"r#ÚeventletÚspawn)rÅr>r,r=r%)r;rÅr<r&rAUs
	'
rAcsStjƒ‰tƒ‰tjˆƒ‡‡‡fdd†ƒ}tj|||ŽdS)aoPassthrough method for eventlet.spawn_n.

    This utility exists so that it can be stubbed for testing without
    interfering with the service spawns.

    It will also grab the context from the threadlocal store and add it to
    the store on the new thread.  This allows for continuity in logging the
    context when using this method to spawn a new thread.
    cs@ˆdk	rˆjƒˆr/tr/tjˆˆ||ŽdS)N)r9r7r:)r>r,)r;rÅr<r%r&r=|s


z spawn_n.<locals>.context_wrapperN)r>r?r8r"r#r@Úspawn_n)rÅr>r,r=r%)r;rÅr<r&rBos
	'
rBcCs&t|tjƒsdS|jƒdkS)z/Check if a string represents a None value.
    FZnone)rYr<r1rÐ)rÚr%r%r&Úis_none_string‰srCcCs:d}|dk	r6|jƒjƒ}|dkr6d}|S)NFÚdisabledT)rÑrÐ)Zauto_disk_config_rawZauto_disk_config_disabledZadc_loweredr%r%r&Úis_auto_disk_config_disabled’srEcCs%|dkrt|ƒ}|jdƒS)NZimage_auto_disk_config)rrh)rZsys_metar%r%r&Ú"get_auto_disk_config_from_instance›srFcCs
|jdƒS)NZauto_disk_config)rh)Zimage_propertiesr%r%r&Ú%get_auto_disk_config_from_image_props¡srGcCsi}td}xat|jdiƒjƒƒD]A\}}|tkrJq/ttj|ƒdƒ}||||<q/Wx‡tD]}|j|ƒ}|dkrÝ|rÝ|jdƒdkrÄ|d}nt	|pÐd|dƒ}|dkrìq{||||<q{W|S)	Nz%sÚ
propertiesrårrZvhdZroot_gbr)
ÚSM_IMAGE_PROP_PREFIXr»rhr¼ÚSM_SKIP_KEYSÚ
safe_truncater<r=ÚSM_INHERITABLE_KEYSÚmax)Ú
image_metaZflavorÚsystem_metaZ
prefix_formatrÃr˜rßr%r%r&Úget_system_metadata_from_image¥s"
+

rPcCsÄi}i}t|tƒs-t|ddƒ}x†t|jƒƒD]r\}}|dkr[q@|jtƒr€|ttƒd…}|tkrq@|t	kr¨|||<q@|||<q@W||d<|S)NrTrH)
rYrÔrr»r¼Ú
startswithrIr’rJrL)rOrNrHrÃr˜r%r%r&Úget_image_from_system_metadataÁs 

rRcCs—tj|jdiƒƒ}d|i}|jddƒtj|d<xBtD]:}|j|dƒ}|d	krKt|p{dƒ||<qKWd|d<|S)
NZvolume_image_metadatarHrrrrÚactiveÚstatus)rzmin_disk)rñrhr
ZGiÚVIM_IMAGE_ATTRIBUTESr:r[)ÚvolumerHrNrØrÚr%r%r&Úget_image_metadata_from_volumeÞs

rWcCs4t|tjƒr!|jdƒ}tj|ƒjƒS)zƒReturns string that represents MD5 hash of base_str (in hex format).

    If base_str is a Unicode string, encode it to UTF-8.
    zutf-8)rYr<r=r—ÚhashlibÚmd5Ú	hexdigest)Úbase_strr%r%r&Úget_hash_str÷sr\cCs4t|tjƒr!|jdƒ}tj|ƒjƒS)a@Returns string that represents sha256 hash of base_str (in hex format).

    sha1 and md5 are known to be breakable, so sha256 is a better option
    when the hash is being used for security purposes. If hashing passwords
    or anything else that needs to be retained for a long period a salted
    hash is better.
    zutf-8)rYr<r=r—rXÚsha256rZ)r[r%r%r&Úget_sha256_strsr^cCs+t|ƒ}tjs'tj|dƒ}|S)z½Returns a string representation of an object converted to unicode.

    In the case of python 3, this just returns the repr() of the object,
    else it converts the repr() to unicode.
    zutf-8)Úreprr<rÌr=)r´Zobj_reprr%r%r&Úget_obj_repr_unicodes	r`c
st|tƒr|g}‡fdd†‰dd„‰‡‡fdd†}g}x­|D]¥}ˆdkrŽ|dkr|d	}|j|iƒ}x |D]}||||ƒ}q•WxIt|jƒƒD]5\}	}
|jd
|	d|
dˆˆ|ƒiƒqÄWqXW|S)
amGet all metadata for a list of resources after filtering.

    Search_filts is a list of dictionaries, where the values in the dictionary
    can be string or regex string, or a list of strings/regex strings.

    Let's call a dict a 'filter block' and an item in the dict
    a 'filter'. A tag is returned if it matches ALL the filters in
    a filter block. If more than one values are specified for a
    filter, a tag is returned if it matches ATLEAST ONE value of the filter. If
    more than one filter blocks are specified, the tag should match ALL the
    filter blocks.

    For example:

        search_filts = [{'key': ['key1', 'key2'], 'value': 'val1'},
                        {'value': 'val2'}]

    The filter translates to 'match any tag for which':
        ((key=key1 AND value=val1) OR (key=key2 AND value=val1)) AND
            (value=val2)

    This example filter will never match a tag.

        :param resource_type: The resource type as a string, e.g. 'instance'
        :param resource_list: List of resource objects
        :param search_filts: Filters to filter metadata to be returned. Can be
            dict (e.g. {'key': 'env', 'value': 'prod'}, or a list of dicts
            (e.g. [{'key': 'env'}, {'value': 'beta'}]. Note that the values
            of the dict can be regular expressions.
        :param metadata_type: Provided to search for a specific metadata type
            (e.g. 'system_metadata')

        :returns: List of dicts where each dict is of the form {'key':
            'somekey', 'value': 'somevalue', 'instance_id':
            'some-instance-uuid-aaa'} if resource_type is 'instance'.
    csˆdkr|jdƒSdS)NrZuuid)rh)Úresource)Ú
resource_typer%r&Ú_get_idDsz4filter_and_format_resource_metadata.<locals>._get_idcs5t|tƒr|g}t‡fdd†|DƒƒS)Ncs"g|]}tj|ˆƒ‘qSr%)rÎÚmatch)rCÚpattern)Ústringr%r&rEKs	zKfilter_and_format_resource_metadata.<locals>._match_any.<locals>.<listcomp>)rYrBÚany)Zpattern_listrfr%)rfr&Ú
_match_anyHs	z7filter_and_format_resource_metadata.<locals>._match_anyc	sê|jdgƒ}|jdgƒ}|jdgƒ}i}|rXˆ|ƒ|krXiSx‹t|jƒƒD]w\}}|r©|r©ˆ||ƒr©ˆ||ƒr©qkn/|r¿ˆ||ƒsk|r؈||ƒrØqk|||<qkW|S)NZresource_idrÃr˜)rhr»r¼)	raZsearch_filtZinput_metadataZidsZkeys_filterZ
values_filterZoutput_metadataÚkÚv)rcrhr%r&Ú_filter_metadataNs z=filter_and_format_resource_metadata.<locals>._filter_metadatarNrrÃr˜z%s_id)rYrÔrhr»r¼rj)rbZ
resource_listZsearch_filtsZ
metadata_typerkZformatted_metadata_listÚresrZfiltrirjr%)rcrhrbr&Ú#filter_and_format_resource_metadatas"'	

rmcCsntj|ƒd|…}d}xH|siytj|ƒ}d}Wq"tk
re|dd…}Yq"Xq"W|S)zpSafely truncates unicode strings such that their encoded length is
    no greater than the length provided.
    NFTrKrœ)rZsafe_encodeZsafe_decodeÚUnicodeDecodeError)r˜r“Zb_valueZ	decode_okZu_valuer%r%r&rK|s	

rKc
Cs­|rt|ƒd}tjj|ƒ}tj|iƒ}|sY||jddƒkrŸtjd|ƒt	|ƒ}|j
ƒ|d<WdQRX||d<d}||dfS)z¿Read from a file if it has been modified.

    :param force_reload: Whether to reload the file.
    :returns: A tuple with a boolean specifying if the data is fresh
              or not.
    FÚmtimerzReloading cached file %sÚdataNT)Údelete_cached_filerér¯ÚgetmtimeÚ_FILE_CACHEÚ
setdefaultrhr]ÚdebugÚopenÚread)ÚfilenameZforce_reloadZreloadedroÚ
cache_infoZfapr%r%r&Úread_cached_files	

rzcCs|tkrt|=dS)zLDelete cached file if present.

    :param filename: filename to delete
    N)rs)rxr%r%r&rq©srqcCsb|stjƒ}|jdƒ}|jr<|jjdƒnd}||dkrWdn|7}|S)zsCurrent time as ISO string,
    as timeutils.isotime() is deprecated

    :returns: Current time in ISO format
    z%Y-%m-%dT%H:%M:%SNÚUTCú	UTC+00:00ÚZ)zUTCr|)rrƒÚstrftimeÚtzinfoÚtzname)ÚatZdate_stringÚtzr%r%r&Úisotime´s!rƒcCs
|jdƒS)Nz%Y-%m-%dT%H:%M:%S.%f)r~)rr%r%r&ÚstrtimeÂsr„cCsÑ|jr|jS|jdkrEy|jƒjSWntk
rDYnXy|jƒSWntjk
rjYnXt|j	ƒ}x=|D]5}||_	y|jƒSWqtjk
rµYqXqWtjd|ƒ‚dS)añGet the endpoint URL represented by a keystoneauth1 Adapter.

    This method is equivalent to what

        ksa_adapter.get_endpoint()

    should do, if it weren't for a panoply of bugs.

    :param ksa_adapter: keystoneauth1.adapter.Adapter, appropriately set up
                        with an endpoint_override; or service_type, interface
                        (list) and auth/service_catalog.
    :return: String endpoint URL.
    :raise EndpointNotFound: If endpoint discovery fails.
    ZimagezICould not find requested endpoint for any of the following interfaces: %sN)
Zendpoint_overrideZservice_typeZget_endpoint_dataZcatalog_urlÚAttributeErrorÚget_endpointÚks_excZEndpointNotFoundr»Ú	interface)Zksa_adapterZ
interfacesrˆr%r%r&r†Æs*	


		r†c%Csåttdƒs tjdƒdStjj|dƒ}d}d}z]yvtj|tjtjBtj	Bƒ}d}t
j
d|ƒ}|jd|ƒtj||ƒtjd	d
|iƒWnàtk
rH}zl|j
t
jkrtjdd
|d|iƒd}n0tjƒ!tjd
d
|d|iƒWdQRXWYdd}~XnUtk
rœ}z5tjƒ!tjd
d
|d|iƒWdQRXWYdd}~XnXWd|dk	rºtj|ƒytj|ƒWntk
rßYnXX|S)NÚO_DIRECTz/This python runtime does not support direct I/OFz.directio.testTirKóxz#Path '%(path)s' supports direct I/Or¯z5Path '%(path)s' does not support direct I/O: '%(ex)s'Úexz7Error on '%(path)s' while checking direct I/O: '%(ex)s'rœ)rÓrér]rur¯r\rvÚO_CREATÚO_WRONLYr‰ÚmmapÚwriter÷ÚerrnoÚEINVALr	rr Ú	ExceptionÚcloseÚunlink)ÚdirpathÚtestfileZhasDirectIOÚfdZ
align_sizeÚmrùr%r%r&Úsupports_direct_ioûsB
#			
	,
	1

r™)úmin_ramúmin_diskúdisk_formatr)rrrr)rrzsizer rrœršr›)rsrtru)}rÚ
contextlibrñr…rr"rXr±rŽrérºrbrÎrõr¿rór_r@Z
keystoneauth1rr‡rZ
ks_loadingrZoslo_concurrencyrrZoslo_contextrr>Zoslo_logrrWZoslo_messagingr)Z
oslo_utilsrr	r
rrr
r<Z	six.movesrZ
dmapi.confrírZ
dmapi.i18nrrrrrZ
try_importr7Úconfr"Ú	getLoggerr.r]Z_IS_NEUTRONZsynchronized_with_prefixrfrIrLrJrUrsr'rÞr(r1r-rmr*rrZDEFAULT_PASSWORD_SYMBOLSrŒr•r™r£r¨rªr­r°r¶rÒÚcontextmanagerrárçrïròrûrýrrrrrr%r&r3r5r8rArBrCrErFrGrPrRrWr\r^r`rmrKrzrqrƒr„r†r™r%r%r%r&Ú<module>sÔ"
k\%0(1
	
		


a5