<s> """<STR_LIT>""" <EOL> import argparse <EOL> import csv <EOL> import functools <EOL> import operator <EOL> import xml . etree . ElementTree as etree <EOL> import libvirt <EOL> class NoPrivateDHCPInterfaceException ( Exception ) : <EOL> pass <EOL> class NoDHCPLeaseException ( Exception ) : <EOL> pass <EOL> def libvirt_conn ( f ) : <EOL> @ functools . wraps ( f ) <EOL> def wrapper ( * args , ** kwargs ) : <EOL> conn = libvirt . openReadOnly ( '<STR_LIT>' ) <EOL> return f ( conn , * args , ** kwargs ) <EOL> return wrapper <EOL> @ libvirt_conn <EOL> def get_vir_network_dhcp_lease ( conn , vm_name ) : <EOL> """<STR_LIT>""" <EOL> network = conn . networkLookupByName ( '<STR_LIT>' ) <EOL> dhcp_leases = libvirt . virNetwork . DHCPLeases ( network ) <EOL> vm_dhcp_leases = filter ( lambda lease : lease [ '<STR_LIT>' ] == vm_name , <EOL> dhcp_leases ) <EOL> newest_vm_dhcp_lease = sorted ( vm_dhcp_leases , <EOL> key = operator . itemgetter ( '<STR_LIT>' ) , <EOL> reverse = True ) [ <NUM_LIT:0> ] [ '<STR_LIT>' ] <EOL> return newest_vm_dhcp_lease <EOL> def get_mac_address ( conn , domain_name ) : <EOL> """<STR_LIT>""" <EOL> domain = conn . lookupByName ( domain_name ) <EOL> domain_xml = domain . XMLDesc ( ) <EOL> domain_tree = etree . fromstring ( domain_xml ) <EOL> devices = domain_tree . find ( '<STR_LIT>' ) <EOL> interfaces = devices . iterfind ( '<STR_LIT>' ) <EOL> for interface in interfaces : <EOL> source = interface . find ( '<STR_LIT:source>' ) <EOL> if source is None or source . get ( '<STR_LIT>' ) != '<STR_LIT>' : <EOL> continue <EOL> mac_element = interface . find ( '<STR_LIT>' ) <EOL> mac_address = mac_element . get ( '<STR_LIT:address>' ) <EOL> return mac_address <EOL> raise NoPrivateDHCPInterfaceException ( ) <EOL> @ libvirt_conn <EOL> def get_dnsmasq_dhcp_lease ( conn , vm_name ) : <EOL> """<STR_LIT>""" <EOL> domain_name = '<STR_LIT>' + vm_name <EOL> mac_address = get_mac_address ( conn , domain_name ) <EOL> with open ( <EOL> '<STR_LIT>' <EOL> ) as leases_file : <EOL> reader = csv . reader ( leases_file , delimiter = '<STR_LIT:U+0020>' ) <EOL> for row in reader : <EOL> lease_mac , lease_ip , lease_vm_name = row [ <NUM_LIT:1> : <NUM_LIT:4> ] <EOL> if not ( lease_mac == mac_address and lease_vm_name == vm_name ) : <EOL> continue <EOL> return lease_ip <EOL> raise NoDHCPLeaseException ( ) <EOL> def main ( ) : <EOL> parser = argparse . ArgumentParser ( ) <EOL> parser . add_argument ( '<STR_LIT>' , help = '<STR_LIT>' ) <EOL> args = parser . parse_args ( ) <EOL> vm_name = args . vm_name <EOL> if libvirt . getVersion ( ) >= <NUM_LIT> : <EOL> newest_dhcp_lease = get_vir_network_dhcp_lease ( vm_name ) <EOL> else : <EOL> newest_dhcp_lease = get_dnsmasq_dhcp_lease ( vm_name ) <EOL> print ( newest_dhcp_lease ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> main ( ) </s>
