idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
37,500
def builder_inited ( app ) : templates_dir = os . path . join ( os . path . dirname ( __file__ ) , '_templates' ) app . builder . templates . pathchain . insert ( 0 , templates_dir ) app . builder . templates . loaders . insert ( 0 , SphinxFileSystemLoader ( templates_dir ) ) app . builder . templates . templatepathlen += 1 if '**' not in app . config . html_sidebars : app . config . html_sidebars [ '**' ] = StandaloneHTMLBuilder . default_sidebars + [ 'versions.html' ] elif 'versions.html' not in app . config . html_sidebars [ '**' ] : app . config . html_sidebars [ '**' ] . append ( 'versions.html' )
Update the Sphinx builder .
37,501
def env_updated ( cls , app , env ) : if cls . ABORT_AFTER_READ : config = { n : getattr ( app . config , n ) for n in ( a for a in dir ( app . config ) if a . startswith ( 'scv_' ) ) } config [ 'found_docs' ] = tuple ( str ( d ) for d in env . found_docs ) config [ 'master_doc' ] = str ( app . config . master_doc ) cls . ABORT_AFTER_READ . put ( config ) sys . exit ( 0 )
Abort Sphinx after initializing config and discovering all pages to build .
37,502
def html_page_context ( cls , app , pagename , templatename , context , doctree ) : assert templatename or doctree cls . VERSIONS . context = context versions = cls . VERSIONS this_remote = versions [ cls . CURRENT_VERSION ] banner_main_remote = versions [ cls . BANNER_MAIN_VERSION ] if cls . SHOW_BANNER else None context [ 'bitbucket_version' ] = cls . CURRENT_VERSION context [ 'current_version' ] = cls . CURRENT_VERSION context [ 'github_version' ] = cls . CURRENT_VERSION context [ 'html_theme' ] = app . config . html_theme context [ 'scv_banner_greatest_tag' ] = cls . BANNER_GREATEST_TAG context [ 'scv_banner_main_ref_is_branch' ] = banner_main_remote [ 'kind' ] == 'heads' if cls . SHOW_BANNER else None context [ 'scv_banner_main_ref_is_tag' ] = banner_main_remote [ 'kind' ] == 'tags' if cls . SHOW_BANNER else None context [ 'scv_banner_main_version' ] = banner_main_remote [ 'name' ] if cls . SHOW_BANNER else None context [ 'scv_banner_recent_tag' ] = cls . BANNER_RECENT_TAG context [ 'scv_is_branch' ] = this_remote [ 'kind' ] == 'heads' context [ 'scv_is_greatest_tag' ] = this_remote == versions . greatest_tag_remote context [ 'scv_is_recent_branch' ] = this_remote == versions . recent_branch_remote context [ 'scv_is_recent_ref' ] = this_remote == versions . recent_remote context [ 'scv_is_recent_tag' ] = this_remote == versions . recent_tag_remote context [ 'scv_is_root' ] = cls . IS_ROOT context [ 'scv_is_tag' ] = this_remote [ 'kind' ] == 'tags' context [ 'scv_show_banner' ] = cls . SHOW_BANNER context [ 'versions' ] = versions context [ 'vhasdoc' ] = versions . vhasdoc context [ 'vpathto' ] = versions . vpathto if cls . SHOW_BANNER and 'body' in context : parsed = app . builder . templates . render ( 'banner.html' , context ) context [ 'body' ] = parsed + context [ 'body' ] css_files = context . setdefault ( 'css_files' , list ( ) ) if '_static/banner.css' not in css_files : css_files . append ( '_static/banner.css' ) if STATIC_DIR not in app . config . html_static_path : app . config . html_static_path . append ( STATIC_DIR ) if app . config . html_last_updated_fmt is not None : file_path = app . env . doc2path ( pagename ) if os . path . isfile ( file_path ) : lufmt = app . config . html_last_updated_fmt or getattr ( locale , '_' ) ( '%b %d, %Y' ) mtime = datetime . datetime . fromtimestamp ( os . path . getmtime ( file_path ) ) context [ 'last_updated' ] = format_date ( lufmt , mtime , language = app . config . language , warn = app . warn )
Update the Jinja2 HTML context exposes the Versions class instance to it .
37,503
def cli ( config , ** options ) : def pre ( rel_source ) : if not NO_EXECUTE : setup_logging ( verbose = config . verbose , colors = not config . no_colors ) log = logging . getLogger ( __name__ ) if config . chdir : os . chdir ( config . chdir ) log . debug ( 'Working directory: %s' , os . getcwd ( ) ) else : config . update ( dict ( chdir = os . getcwd ( ) ) , overwrite = True ) try : config . update ( dict ( git_root = get_root ( config . git_root or os . getcwd ( ) ) ) , overwrite = True ) except GitError as exc : log . error ( exc . message ) log . error ( exc . output ) raise HandledError if config . no_local_conf : config . update ( dict ( local_conf = None ) , overwrite = True ) elif not config . local_conf : candidates = [ p for p in ( os . path . join ( s , 'conf.py' ) for s in rel_source ) if os . path . isfile ( p ) ] if candidates : config . update ( dict ( local_conf = candidates [ 0 ] ) , overwrite = True ) else : log . debug ( "Didn't find a conf.py in any REL_SOURCE." ) elif os . path . basename ( config . local_conf ) != 'conf.py' : log . error ( 'Path "%s" must end with conf.py.' , config . local_conf ) raise HandledError config [ 'pre' ] = pre config . update ( options )
Build versioned Sphinx docs for every branch and tag pushed to origin .
37,504
def build_options ( func ) : func = click . option ( '-a' , '--banner-greatest-tag' , is_flag = True , help = 'Override banner-main-ref to be the tag with the highest version number.' ) ( func ) func = click . option ( '-A' , '--banner-recent-tag' , is_flag = True , help = 'Override banner-main-ref to be the most recent committed tag.' ) ( func ) func = click . option ( '-b' , '--show-banner' , help = 'Show a warning banner.' , is_flag = True ) ( func ) func = click . option ( '-B' , '--banner-main-ref' , help = "Don't show banner on this ref and point banner URLs to this ref. Default master." ) ( func ) func = click . option ( '-i' , '--invert' , help = 'Invert/reverse order of versions.' , is_flag = True ) ( func ) func = click . option ( '-p' , '--priority' , type = click . Choice ( ( 'branches' , 'tags' ) ) , help = "Group these kinds of versions at the top (for themes that don't separate them)." ) ( func ) func = click . option ( '-r' , '--root-ref' , help = 'The branch/tag at the root of DESTINATION. Will also be in subdir. Default master.' ) ( func ) func = click . option ( '-s' , '--sort' , multiple = True , type = click . Choice ( ( 'semver' , 'alpha' , 'time' ) ) , help = 'Sort versions. Specify multiple times to sort equal values of one kind.' ) ( func ) func = click . option ( '-t' , '--greatest-tag' , is_flag = True , help = 'Override root-ref to be the tag with the highest version number.' ) ( func ) func = click . option ( '-T' , '--recent-tag' , is_flag = True , help = 'Override root-ref to be the most recent committed tag.' ) ( func ) func = click . option ( '-w' , '--whitelist-branches' , multiple = True , help = 'Whitelist branches that match the pattern. Can be specified more than once.' ) ( func ) func = click . option ( '-W' , '--whitelist-tags' , multiple = True , help = 'Whitelist tags that match the pattern. Can be specified more than once.' ) ( func ) return func
Add build Click options to function .
37,505
def override_root_main_ref ( config , remotes , banner ) : log = logging . getLogger ( __name__ ) greatest_tag = config . banner_greatest_tag if banner else config . greatest_tag recent_tag = config . banner_recent_tag if banner else config . recent_tag if greatest_tag or recent_tag : candidates = [ r for r in remotes if r [ 'kind' ] == 'tags' ] if candidates : multi_sort ( candidates , [ 'semver' if greatest_tag else 'time' ] ) config . update ( { 'banner_main_ref' if banner else 'root_ref' : candidates [ 0 ] [ 'name' ] } , overwrite = True ) else : flag = '--banner-main-ref' if banner else '--root-ref' log . warning ( 'No git tags with docs found in remote. Falling back to %s value.' , flag ) ref = config . banner_main_ref if banner else config . root_ref return ref in [ r [ 'name' ] for r in remotes ]
Override root_ref or banner_main_ref with tags in config if user requested .
37,506
def push ( ctx , config , rel_source , dest_branch , rel_dest , ** options ) : if 'pre' in config : config . pop ( 'pre' ) ( rel_source ) config . update ( { k : v for k , v in options . items ( ) if v } ) if config . local_conf : config . update ( read_local_conf ( config . local_conf ) , ignore_set = True ) if NO_EXECUTE : raise RuntimeError ( config , rel_source , dest_branch , rel_dest ) log = logging . getLogger ( __name__ ) for _ in range ( PUSH_RETRIES ) : with TempDir ( ) as temp_dir : log . info ( 'Cloning %s into temporary directory...' , dest_branch ) try : clone ( config . git_root , temp_dir , config . push_remote , dest_branch , rel_dest , config . grm_exclude ) except GitError as exc : log . error ( exc . message ) log . error ( exc . output ) raise HandledError log . info ( 'Building docs...' ) ctx . invoke ( build , rel_source = rel_source , destination = os . path . join ( temp_dir , rel_dest ) ) versions = config . pop ( 'versions' ) log . info ( 'Attempting to push to branch %s on remote repository.' , dest_branch ) try : if commit_and_push ( temp_dir , config . push_remote , versions ) : return except GitError as exc : log . error ( exc . message ) log . error ( exc . output ) raise HandledError log . warning ( 'Failed to push to remote repository. Retrying in %d seconds...' , PUSH_SLEEP ) time . sleep ( PUSH_SLEEP ) log . error ( 'Ran out of retries, giving up.' ) raise HandledError
Build locally and then push to remote branch .
37,507
def get_params ( self , ctx ) : self . params . sort ( key = self . custom_sort ) return super ( ClickGroup , self ) . get_params ( ctx )
Sort order of options before displaying .
37,508
def main ( self , * args , ** kwargs ) : argv = kwargs . pop ( 'args' , click . get_os_args ( ) ) if '--' in argv : pos = argv . index ( '--' ) argv , self . overflow = argv [ : pos ] , tuple ( argv [ pos + 1 : ] ) else : argv , self . overflow = argv , tuple ( ) return super ( ClickGroup , self ) . main ( args = argv , * args , ** kwargs )
Main function called by setuptools .
37,509
def invoke ( self , ctx ) : if self . overflow : ctx . ensure_object ( Config ) . update ( dict ( overflow = self . overflow ) ) return super ( ClickGroup , self ) . invoke ( ctx )
Inject overflow arguments into context state .
37,510
def from_context ( cls ) : try : ctx = click . get_current_context ( ) except RuntimeError : return cls ( ) return ctx . find_object ( cls )
Retrieve this class instance from the current Click context .
37,511
def update ( self , params , ignore_set = False , overwrite = False ) : log = logging . getLogger ( __name__ ) valid = { i [ 0 ] for i in self } for key , value in params . items ( ) : if not hasattr ( self , key ) : raise AttributeError ( "'{}' object has no attribute '{}'" . format ( self . __class__ . __name__ , key ) ) if key not in valid : message = "'{}' object does not support item assignment on '{}'" raise AttributeError ( message . format ( self . __class__ . __name__ , key ) ) if key in self . _already_set : if ignore_set : log . debug ( '%s already set in config, skipping.' , key ) continue if not overwrite : message = "'{}' object does not support item re-assignment on '{}'" raise AttributeError ( message . format ( self . __class__ . __name__ , key ) ) setattr ( self , key , value ) self . _already_set . add ( key )
Set instance values from dictionary .
37,512
def cleanup ( self ) : shutil . rmtree ( self . name , onerror = lambda * a : os . chmod ( a [ 1 ] , __import__ ( 'stat' ) . S_IWRITE ) or os . unlink ( a [ 1 ] ) ) if os . path . exists ( self . name ) : raise IOError ( 17 , "File exists: '{}'" . format ( self . name ) )
Recursively delete directory .
37,513
def update_subports ( self , port ) : trunk_details = port . get ( 'trunk_details' ) subports = trunk_details [ 'sub_ports' ] host_id = port . get ( bc . dns . DNSNAME ) context = bc . get_context ( ) el_context = context . elevated ( ) for subport in subports : bc . get_plugin ( ) . update_port ( el_context , subport [ 'port_id' ] , { 'port' : { bc . portbindings . HOST_ID : host_id , 'device_owner' : bc . trunk_consts . TRUNK_SUBPORT_OWNER } } ) trunk_obj = bc . trunk_objects . Trunk . get_object ( el_context , id = trunk_details [ 'trunk_id' ] ) trunk_obj . update ( status = bc . trunk_consts . ACTIVE_STATUS )
Set port attributes for trunk subports .
37,514
def read_static_uplink ( self ) : if self . node_list is None or self . node_uplink_list is None : return for node , port in zip ( self . node_list . split ( ',' ) , self . node_uplink_list . split ( ',' ) ) : if node . strip ( ) == self . host_name : self . static_uplink = True self . static_uplink_port = port . strip ( ) return
Read the static uplink from file if given .
37,515
def vdp_vlan_change_cb ( self , port_uuid , lvid , vdp_vlan , fail_reason ) : LOG . info ( "Vlan change CB lvid %(lvid)s VDP %(vdp)s" , { 'lvid' : lvid , 'vdp' : vdp_vlan } ) self . update_vm_result ( port_uuid , constants . RESULT_SUCCESS , lvid = lvid , vdp_vlan = vdp_vlan , fail_reason = fail_reason )
Callback function for updating the VDP VLAN in DB .
37,516
def process_bulk_vm_event ( self , msg , phy_uplink ) : LOG . info ( "In processing Bulk VM Event status %s" , msg ) time . sleep ( 3 ) if ( not self . uplink_det_compl or phy_uplink not in self . ovs_vdp_obj_dict ) : LOG . error ( "Uplink Port Event not received," "yet in bulk process" ) return ovs_vdp_obj = self . ovs_vdp_obj_dict [ phy_uplink ] for vm_dict in msg . msg_dict . get ( 'vm_bulk_list' ) : if vm_dict [ 'status' ] == 'down' : ovs_vdp_obj . pop_local_cache ( vm_dict [ 'port_uuid' ] , vm_dict [ 'vm_mac' ] , vm_dict [ 'net_uuid' ] , vm_dict [ 'local_vlan' ] , vm_dict [ 'vdp_vlan' ] , vm_dict [ 'segmentation_id' ] ) vm_msg = VdpQueMsg ( constants . VM_MSG_TYPE , port_uuid = vm_dict [ 'port_uuid' ] , vm_mac = vm_dict [ 'vm_mac' ] , net_uuid = vm_dict [ 'net_uuid' ] , segmentation_id = vm_dict [ 'segmentation_id' ] , status = vm_dict [ 'status' ] , oui = vm_dict [ 'oui' ] , phy_uplink = phy_uplink ) self . process_vm_event ( vm_msg , phy_uplink )
Process the VM bulk event usually after a restart .
37,517
def is_openstack_running ( self ) : try : if ( ovs_vdp . is_bridge_present ( self . br_ex , self . root_helper ) and ovs_vdp . is_bridge_present ( self . br_integ , self . root_helper ) ) : return True else : return False except Exception as e : LOG . error ( "Exception in is_openstack_running %s" , str ( e ) ) return False
Currently it just checks for the presence of both the bridges .
37,518
def _fill_topology_cfg ( self , topo_dict ) : cfg_dict = { } if topo_dict . bond_member_ports is not None : cfg_dict . update ( { 'bond_member_ports' : topo_dict . bond_member_ports } ) if topo_dict . bond_interface is not None : cfg_dict . update ( { 'bond_interface' : topo_dict . bond_interface } ) return cfg_dict
Fills the extra configurations in the topology .
37,519
def uplink_bond_intf_process ( self ) : bond_intf = sys_utils . get_bond_intf ( self . phy_uplink ) if bond_intf is None : return False self . save_uplink ( fail_reason = constants . port_transition_bond_down_reason ) self . process_uplink_ongoing = True upl_msg = VdpQueMsg ( constants . UPLINK_MSG_TYPE , status = 'down' , phy_uplink = self . phy_uplink , br_int = self . br_integ , br_ex = self . br_ex , root_helper = self . root_helper ) self . que . enqueue ( constants . Q_UPL_PRIO , upl_msg ) self . phy_uplink = None self . veth_intf = None self . uplink_det_compl = False self . save_uplink ( uplink = bond_intf , fail_reason = constants . port_transition_bond_up_reason ) self . phy_uplink = bond_intf self . process_uplink_ongoing = True upl_msg = VdpQueMsg ( constants . UPLINK_MSG_TYPE , status = 'up' , phy_uplink = self . phy_uplink , br_int = self . br_integ , br_ex = self . br_ex , root_helper = self . root_helper ) self . que . enqueue ( constants . Q_UPL_PRIO , upl_msg ) return True
Process the case when uplink interface becomes part of a bond .
37,520
def check_periodic_bulk_vm_notif_rcvd ( self ) : if not self . bulk_vm_rcvd_flag : if self . bulk_vm_check_cnt >= 1 : self . bulk_vm_check_cnt = 0 self . save_uplink ( uplink = self . phy_uplink , veth_intf = self . veth_intf ) LOG . info ( "Doing save_uplink again to request " "Bulk VM's" ) else : LOG . info ( "Bulk VM not received, incrementing count" ) self . bulk_vm_check_cnt += 1
Bulk VM check handler called from periodic uplink detection .
37,521
def static_uplink_detect ( self , veth ) : LOG . info ( "In static_uplink_detect %(veth)s" , { 'veth' : veth } ) if self . static_uplink_first : self . static_uplink_first = False if self . phy_uplink is not None and ( self . phy_uplink != self . static_uplink_port ) : return 'down' if veth is None : return self . static_uplink_port else : return 'normal'
Return the static uplink based on argument passed .
37,522
def get_hosting_device_config ( self , client , hosting_device_id ) : return client . get ( ( self . resource_path + HOSTING_DEVICE_CONFIG ) % hosting_device_id )
Get config of hosting_device .
37,523
def get_client_class ( self , client_class_name ) : request_url = self . _build_url ( [ 'ClientClass' , client_class_name ] ) return self . _do_request ( 'GET' , request_url )
Returns a specific client class details from CPNR server .
37,524
def get_vpn ( self , vpn_name ) : request_url = self . _build_url ( [ 'VPN' , vpn_name ] ) return self . _do_request ( 'GET' , request_url )
Returns a specific VPN name details from CPNR server .
37,525
def get_scopes ( self , vpnid = '.*' ) : request_url = self . _build_url ( [ 'Scope' ] , vpn = vpnid ) return self . _do_request ( 'GET' , request_url )
Returns a list of all the scopes from CPNR server .
37,526
def get_scope ( self , scope_name ) : request_url = self . _build_url ( [ 'Scope' , scope_name ] ) return self . _do_request ( 'GET' , request_url )
Returns a specific scope name details from CPNR server .
37,527
def get_client_entry ( self , client_entry_name ) : request_url = self . _build_url ( [ 'ClientEntry' , client_entry_name ] ) return self . _do_request ( 'GET' , request_url )
Returns a specific client entry name details from CPNR server .
37,528
def release_address ( self , address , vpnid ) : query = address + "?action=releaseAddress&vpnId=" + vpnid request_url = self . _build_url ( [ 'Lease' , query ] ) return self . _do_request ( 'DELETE' , request_url )
Release a specific lease called after delete_client_entry
37,529
def qsize ( self , qname ) : if qname in self . _queues : return self . _queues [ qname ] . qsize ( ) else : raise ValueError ( _ ( "queue %s is not defined" ) , qname )
Return the approximate size of the queue .
37,530
def get_nexusport_binding ( port_id , vlan_id , switch_ip , instance_id ) : LOG . debug ( "get_nexusport_binding() called" ) return _lookup_all_nexus_bindings ( port_id = port_id , vlan_id = vlan_id , switch_ip = switch_ip , instance_id = instance_id )
Lists a nexusport binding .
37,531
def get_nexus_switchport_binding ( port_id , switch_ip ) : LOG . debug ( "get_nexus_switchport_binding() called" ) return _lookup_all_nexus_bindings ( port_id = port_id , switch_ip = switch_ip )
Lists all bindings for this switch & port .
37,532
def get_nexusvlan_binding ( vlan_id , switch_ip ) : LOG . debug ( "get_nexusvlan_binding() called" ) return _lookup_all_nexus_bindings ( vlan_id = vlan_id , switch_ip = switch_ip )
Lists a vlan and switch binding .
37,533
def get_reserved_bindings ( vlan_id , instance_id , switch_ip = None , port_id = None ) : LOG . debug ( "get_reserved_bindings() called" ) if port_id : return _lookup_all_nexus_bindings ( vlan_id = vlan_id , switch_ip = switch_ip , instance_id = instance_id , port_id = port_id ) elif switch_ip : return _lookup_all_nexus_bindings ( vlan_id = vlan_id , switch_ip = switch_ip , instance_id = instance_id ) else : return _lookup_all_nexus_bindings ( vlan_id = vlan_id , instance_id = instance_id )
Lists reserved bindings .
37,534
def update_reserved_binding ( vlan_id , switch_ip , instance_id , port_id , is_switch_binding = True , is_native = False , ch_grp = 0 ) : if not port_id : LOG . warning ( "update_reserved_binding called with no state" ) return LOG . debug ( "update_reserved_binding called" ) session = bc . get_writer_session ( ) if is_switch_binding : binding = _lookup_one_nexus_binding ( session = session , vlan_id = vlan_id , switch_ip = switch_ip , instance_id = instance_id ) binding . port_id = port_id else : binding = _lookup_one_nexus_binding ( session = session , vlan_id = vlan_id , switch_ip = switch_ip , instance_id = instance_id , port_id = port_id ) binding . is_native = is_native binding . channel_group = ch_grp session . merge ( binding ) session . flush ( ) return binding
Updates reserved binding .
37,535
def remove_reserved_binding ( vlan_id , switch_ip , instance_id , port_id ) : if not port_id : LOG . warning ( "remove_reserved_binding called with no state" ) return LOG . debug ( "remove_reserved_binding called" ) session = bc . get_writer_session ( ) binding = _lookup_one_nexus_binding ( session = session , vlan_id = vlan_id , switch_ip = switch_ip , instance_id = instance_id , port_id = port_id ) for bind in binding : session . delete ( bind ) session . flush ( ) return binding
Removes reserved binding .
37,536
def add_reserved_switch_binding ( switch_ip , state ) : add_nexusport_binding ( state , const . NO_VLAN_OR_VNI_ID , const . NO_VLAN_OR_VNI_ID , switch_ip , const . RESERVED_NEXUS_SWITCH_DEVICE_ID_R1 )
Add a reserved switch binding .
37,537
def update_reserved_switch_binding ( switch_ip , state ) : update_reserved_binding ( const . NO_VLAN_OR_VNI_ID , switch_ip , const . RESERVED_NEXUS_SWITCH_DEVICE_ID_R1 , state )
Update a reserved switch binding .
37,538
def add_nexusport_binding ( port_id , vlan_id , vni , switch_ip , instance_id , is_native = False , ch_grp = 0 ) : LOG . debug ( "add_nexusport_binding() called" ) session = bc . get_writer_session ( ) binding = nexus_models_v2 . NexusPortBinding ( port_id = port_id , vlan_id = vlan_id , vni = vni , switch_ip = switch_ip , instance_id = instance_id , is_native = is_native , channel_group = ch_grp ) session . add ( binding ) session . flush ( ) return binding
Adds a nexusport binding .
37,539
def remove_nexusport_binding ( port_id , vlan_id , vni , switch_ip , instance_id ) : LOG . debug ( "remove_nexusport_binding() called" ) session = bc . get_writer_session ( ) binding = _lookup_all_nexus_bindings ( session = session , vlan_id = vlan_id , vni = vni , switch_ip = switch_ip , port_id = port_id , instance_id = instance_id ) for bind in binding : session . delete ( bind ) session . flush ( ) return binding
Removes a nexusport binding .
37,540
def update_nexusport_binding ( port_id , new_vlan_id ) : if not new_vlan_id : LOG . warning ( "update_nexusport_binding called with no vlan" ) return LOG . debug ( "update_nexusport_binding called" ) session = bc . get_writer_session ( ) binding = _lookup_one_nexus_binding ( session = session , port_id = port_id ) binding . vlan_id = new_vlan_id session . merge ( binding ) session . flush ( ) return binding
Updates nexusport binding .
37,541
def remove_all_nexusport_bindings ( ) : LOG . debug ( "remove_all_nexusport_bindings() called" ) session = bc . get_writer_session ( ) session . query ( nexus_models_v2 . NexusPortBinding ) . delete ( ) session . flush ( )
Removes all nexusport bindings .
37,542
def _lookup_nexus_bindings ( query_type , session = None , ** bfilter ) : if session is None : session = bc . get_reader_session ( ) query_method = getattr ( session . query ( nexus_models_v2 . NexusPortBinding ) . filter_by ( ** bfilter ) , query_type ) try : bindings = query_method ( ) if bindings : return bindings except sa_exc . NoResultFound : pass raise c_exc . NexusPortBindingNotFound ( ** bfilter )
Look up query_type Nexus bindings matching the filter .
37,543
def add_nexusnve_binding ( vni , switch_ip , device_id , mcast_group ) : LOG . debug ( "add_nexusnve_binding() called" ) session = bc . get_writer_session ( ) binding = nexus_models_v2 . NexusNVEBinding ( vni = vni , switch_ip = switch_ip , device_id = device_id , mcast_group = mcast_group ) session . add ( binding ) session . flush ( ) return binding
Adds a nexus nve binding .
37,544
def remove_nexusnve_binding ( vni , switch_ip , device_id ) : LOG . debug ( "remove_nexusnve_binding() called" ) session = bc . get_writer_session ( ) binding = ( session . query ( nexus_models_v2 . NexusNVEBinding ) . filter_by ( vni = vni , switch_ip = switch_ip , device_id = device_id ) . one ( ) ) if binding : session . delete ( binding ) session . flush ( ) return binding
Remove the nexus nve binding .
37,545
def remove_all_nexusnve_bindings ( ) : LOG . debug ( "remove_all_nexusport_bindings() called" ) session = bc . get_writer_session ( ) session . query ( nexus_models_v2 . NexusNVEBinding ) . delete ( ) session . flush ( )
Removes all nexusnve bindings .
37,546
def _lookup_host_mappings ( query_type , session = None , ** bfilter ) : if session is None : session = bc . get_reader_session ( ) query_method = getattr ( session . query ( nexus_models_v2 . NexusHostMapping ) . filter_by ( ** bfilter ) , query_type ) try : mappings = query_method ( ) if mappings : return mappings except sa_exc . NoResultFound : pass raise c_exc . NexusHostMappingNotFound ( ** bfilter )
Look up query_type Nexus mappings matching the filter .
37,547
def add_host_mapping ( host_id , nexus_ip , interface , ch_grp , is_static ) : LOG . debug ( "add_nexusport_binding() called" ) session = bc . get_writer_session ( ) mapping = nexus_models_v2 . NexusHostMapping ( host_id = host_id , if_id = interface , switch_ip = nexus_ip , ch_grp = ch_grp , is_static = is_static ) try : session . add ( mapping ) session . flush ( ) except db_exc . DBDuplicateEntry : with excutils . save_and_reraise_exception ( ) as ctxt : if is_static : ctxt . reraise = False LOG . debug ( "Duplicate static entry encountered " "host=%(host)s, if=%(if)s, ip=%(ip)s" , { 'host' : host_id , 'if' : interface , 'ip' : nexus_ip } ) return mapping
Add Host to interface mapping entry into mapping data base .
37,548
def remove_host_mapping ( interface , nexus_ip ) : LOG . debug ( "remove_host_mapping() called" ) session = bc . get_writer_session ( ) try : mapping = _lookup_one_host_mapping ( session = session , if_id = interface , switch_ip = nexus_ip ) session . delete ( mapping ) session . flush ( ) except c_exc . NexusHostMappingNotFound : pass
Remove host to interface mapping entry from mapping data base .
37,549
def remove_all_static_host_mappings ( ) : LOG . debug ( "remove_host_mapping() called" ) session = bc . get_writer_session ( ) try : mapping = _lookup_all_host_mappings ( session = session , is_static = True ) for host in mapping : session . delete ( host ) session . flush ( ) except c_exc . NexusHostMappingNotFound : pass
Remove all entries defined in config file from mapping data base .
37,550
def _lookup_vpc_allocs ( query_type , session = None , order = None , ** bfilter ) : if session is None : session = bc . get_reader_session ( ) if order : query_method = getattr ( session . query ( nexus_models_v2 . NexusVPCAlloc ) . filter_by ( ** bfilter ) . order_by ( order ) , query_type ) else : query_method = getattr ( session . query ( nexus_models_v2 . NexusVPCAlloc ) . filter_by ( ** bfilter ) , query_type ) try : vpcs = query_method ( ) if vpcs : return vpcs except sa_exc . NoResultFound : pass raise c_exc . NexusVPCAllocNotFound ( ** bfilter )
Look up query_type Nexus VPC Allocs matching the filter .
37,551
def _get_free_vpcids_on_switches ( switch_ip_list ) : session = bc . get_reader_session ( ) prev_view = aliased ( nexus_models_v2 . NexusVPCAlloc ) query = session . query ( prev_view . vpc_id ) prev_swip = switch_ip_list [ 0 ] for ip in switch_ip_list [ 1 : ] : cur_view = aliased ( nexus_models_v2 . NexusVPCAlloc ) cur_swip = ip query = query . join ( cur_view , sa . and_ ( prev_view . switch_ip == prev_swip , prev_view . active == False , cur_view . switch_ip == cur_swip , cur_view . active == False , prev_view . vpc_id == cur_view . vpc_id ) ) prev_view = cur_view prev_swip = cur_swip unique_vpcids = query . all ( ) shuffle ( unique_vpcids ) return unique_vpcids
Get intersect list of free vpcids in list of switches .
37,552
def update_vpc_entry ( nexus_ips , vpc_id , learned , active ) : LOG . debug ( "update_vpc_entry called" ) session = bc . get_writer_session ( ) with session . begin ( ) : for n_ip in nexus_ips : flipit = not active x = session . execute ( sa . update ( nexus_models_v2 . NexusVPCAlloc ) . values ( { 'learned' : learned , 'active' : active } ) . where ( sa . and_ ( nexus_models_v2 . NexusVPCAlloc . switch_ip == n_ip , nexus_models_v2 . NexusVPCAlloc . vpc_id == vpc_id , nexus_models_v2 . NexusVPCAlloc . active == flipit ) ) ) if x . rowcount != 1 : raise c_exc . NexusVPCAllocNotFound ( switch_ip = n_ip , vpc_id = vpc_id , active = active )
Change active state in vpc_allocate data base .
37,553
def alloc_vpcid ( nexus_ips ) : LOG . debug ( "alloc_vpc() called" ) vpc_id = 0 intersect = _get_free_vpcids_on_switches ( nexus_ips ) for intersect_tuple in intersect : try : update_vpc_entry ( nexus_ips , intersect_tuple . vpc_id , False , True ) vpc_id = intersect_tuple . vpc_id break except Exception : LOG . exception ( "This exception is expected if another controller " "beat us to vpcid %(vpcid)s for nexus %(ip)s" , { 'vpcid' : intersect_tuple . vpc_id , 'ip' : ', ' . join ( map ( str , nexus_ips ) ) } ) return vpc_id
Allocate a vpc id for the given list of switch_ips .
37,554
def free_vpcid_for_switch_list ( vpc_id , nexus_ips ) : LOG . debug ( "free_vpcid_for_switch_list() called" ) if vpc_id != 0 : update_vpc_entry ( nexus_ips , vpc_id , False , False )
Free a vpc id for the given list of switch_ips .
37,555
def free_vpcid_for_switch ( vpc_id , nexus_ip ) : LOG . debug ( "free_vpcid_for_switch() called" ) if vpc_id != 0 : update_vpc_entry ( [ nexus_ip ] , vpc_id , False , False )
Free a vpc id for the given switch_ip .
37,556
def delete_vpcid_for_switch ( vpc_id , switch_ip ) : LOG . debug ( "delete_vpcid_for_switch called" ) session = bc . get_writer_session ( ) vpc = _lookup_one_vpc_allocs ( vpc_id = vpc_id , switch_ip = switch_ip , active = False ) session . delete ( vpc ) session . flush ( )
Removes unused vpcid for a switch .
37,557
def create_process ( cmd , root_helper = None , addl_env = None , log_output = True ) : if root_helper : cmd = shlex . split ( root_helper ) + cmd cmd = map ( str , cmd ) log_output and LOG . info ( "Running command: %s" , cmd ) env = os . environ . copy ( ) if addl_env : env . update ( addl_env ) obj = subprocess_popen ( cmd , shell = False , stdin = subprocess . PIPE , stdout = subprocess . PIPE , stderr = subprocess . PIPE , env = env ) return obj , cmd
Create a process object for the given command .
37,558
def is_intf_up ( intf ) : intf_path = '/' . join ( ( '/sys/class/net' , intf ) ) intf_exist = os . path . exists ( intf_path ) if not intf_exist : LOG . error ( "Unable to get interface %(intf)s, Interface dir " "%(dir)s does not exist" , { 'intf' : intf , 'dir' : intf_path } ) return False try : oper_file = '/' . join ( ( intf_path , 'operstate' ) ) with open ( oper_file , 'r' ) as fd : oper_state = fd . read ( ) . strip ( '\n' ) if oper_state == 'up' : return True except Exception as e : LOG . error ( "Exception in reading %s" , str ( e ) ) return False
Function to check if a interface is up .
37,559
def get_all_run_phy_intf ( ) : intf_list = [ ] base_dir = '/sys/class/net' dir_exist = os . path . exists ( base_dir ) if not dir_exist : LOG . error ( "Unable to get interface list :Base dir %s does not " "exist" , base_dir ) return intf_list dir_cont = os . listdir ( base_dir ) for subdir in dir_cont : dev_dir = base_dir + '/' + subdir + '/' + 'device' dev_exist = os . path . exists ( dev_dir ) if dev_exist : oper_state = is_intf_up ( subdir ) if oper_state is True : intf_list . append ( subdir ) else : LOG . info ( "Dev dir %s does not exist, not physical intf" , dev_dir ) return intf_list
Retrieve all physical interfaces that are operationally up .
37,560
def check_vnic_type_and_vendor_info ( self , vnic_type , profile ) : if vnic_type not in self . supported_sriov_vnic_types : LOG . info ( 'Non SR-IOV vnic_type: %s.' , vnic_type ) return False if not profile : return False return self . _check_for_supported_vendor ( profile )
Checks if this vnic_type and vendor device info are supported .
37,561
def _check_for_supported_vendor ( self , profile ) : vendor_info = profile . get ( 'pci_vendor_info' ) if not vendor_info : return False if vendor_info not in self . supported_pci_devs : return False return True
Checks if the port belongs to a supported vendor .
37,562
def _import_ucsmsdk ( self ) : if not CONF . ml2_cisco_ucsm . ucsm_https_verify : LOG . warning ( const . SSL_WARNING ) from networking_cisco . ml2_drivers . ucsm import ucs_urllib2 ucsmsdkhandle = importutils . import_module ( 'UcsSdk.UcsHandle' ) ucsmsdkhandle . urllib2 = ucs_urllib2 ucsmsdk = importutils . import_module ( 'UcsSdk' ) return ucsmsdk
Imports the Ucsm SDK module .
37,563
def _get_server_name ( self , handle , service_profile_mo , ucsm_ip ) : try : resolved_dest = handle . ConfigResolveDn ( service_profile_mo . PnDn ) server_list = resolved_dest . OutConfig . GetChild ( ) if not server_list : return "" return server_list [ 0 ] . Name except Exception as e : raise cexc . UcsmConfigReadFailed ( ucsm_ip = ucsm_ip , exc = e )
Get the contents of the Name field associated with UCS Server .
37,564
def _create_vlanprofile ( self , handle , vlan_id , ucsm_ip ) : vlan_name = self . make_vlan_name ( vlan_id ) vlan_profile_dest = ( const . VLAN_PATH + const . VLAN_PROFILE_PATH_PREFIX + vlan_name ) try : handle . StartTransaction ( ) vp1 = handle . GetManagedObject ( None , self . ucsmsdk . FabricLanCloud . ClassId ( ) , { self . ucsmsdk . FabricLanCloud . DN : const . VLAN_PATH } ) if not vp1 : LOG . warning ( 'UCS Manager network driver Vlan Profile ' 'path at %s missing' , const . VLAN_PATH ) return False vp2 = handle . AddManagedObject ( vp1 , self . ucsmsdk . FabricVlan . ClassId ( ) , { self . ucsmsdk . FabricVlan . COMPRESSION_TYPE : const . VLAN_COMPRESSION_TYPE , self . ucsmsdk . FabricVlan . DN : vlan_profile_dest , self . ucsmsdk . FabricVlan . SHARING : const . NONE , self . ucsmsdk . FabricVlan . PUB_NW_NAME : "" , self . ucsmsdk . FabricVlan . ID : str ( vlan_id ) , self . ucsmsdk . FabricVlan . MCAST_POLICY_NAME : "" , self . ucsmsdk . FabricVlan . NAME : vlan_name , self . ucsmsdk . FabricVlan . DEFAULT_NET : "no" } ) handle . CompleteTransaction ( ) if vp2 : LOG . debug ( 'UCS Manager network driver Created Vlan ' 'Profile %s at %s' , vlan_name , vlan_profile_dest ) return True except Exception as e : return self . _handle_ucsm_exception ( e , 'Vlan Profile' , vlan_name , ucsm_ip )
Creates VLAN profile to be assosiated with the Port Profile .
37,565
def create_portprofile ( self , profile_name , vlan_id , vnic_type , host_id , trunk_vlans ) : ucsm_ip = self . get_ucsm_ip_for_host ( host_id ) if not ucsm_ip : LOG . info ( 'UCS Manager network driver does not have UCSM IP ' 'for Host_id %s' , str ( host_id ) ) return False with self . ucsm_connect_disconnect ( ucsm_ip ) as handle : if not self . _create_vlanprofile ( handle , vlan_id , ucsm_ip ) : LOG . error ( 'UCS Manager network driver failed to create ' 'Vlan Profile for vlan %s' , str ( vlan_id ) ) return False if trunk_vlans : for vlan in trunk_vlans : if not self . _create_vlanprofile ( handle , vlan , ucsm_ip ) : LOG . error ( 'UCS Manager network driver failed to ' 'create Vlan Profile for vlan %s' , vlan ) return False qos_policy = CONF . ml2_cisco_ucsm . ucsms [ ucsm_ip ] . sriov_qos_policy if qos_policy : LOG . debug ( 'UCS Manager Network driver applying QoS Policy ' '%(qos)s to Port Profile %(port_profile)s' , { 'qos' : qos_policy , 'port_profile' : profile_name } ) if not self . _create_port_profile ( handle , profile_name , vlan_id , vnic_type , ucsm_ip , trunk_vlans , qos_policy ) : LOG . error ( 'UCS Manager network driver failed to create ' 'Port Profile %s' , profile_name ) return False return True
Top level method to create Port Profiles on the UCS Manager .
37,566
def update_serviceprofile ( self , host_id , vlan_id ) : ucsm_ip = self . get_ucsm_ip_for_host ( host_id ) if not ucsm_ip : LOG . info ( 'UCS Manager network driver does not have UCSM IP ' 'for Host_id %s' , str ( host_id ) ) return False service_profile = self . ucsm_sp_dict . get ( ( ucsm_ip , host_id ) ) if service_profile : LOG . debug ( 'UCS Manager network driver Service Profile : %s' , service_profile ) else : LOG . info ( 'UCS Manager network driver does not support ' 'Host_id %s' , host_id ) return False with self . ucsm_connect_disconnect ( ucsm_ip ) as handle : if not self . _create_vlanprofile ( handle , vlan_id , ucsm_ip ) : LOG . error ( 'UCS Manager network driver failed to create ' 'Vlan Profile for vlan %s' , str ( vlan_id ) ) return False if not self . _update_service_profile ( handle , service_profile , vlan_id , ucsm_ip ) : LOG . error ( 'UCS Manager network driver failed to update ' 'Service Profile %(service_profile)s in UCSM ' '%(ucsm_ip)s' , { 'service_profile' : service_profile , 'ucsm_ip' : ucsm_ip } ) return False return True
Top level method to update Service Profiles on UCS Manager .
37,567
def _delete_port_profile ( self , handle , port_profile , ucsm_ip ) : try : self . _delete_port_profile_from_ucsm ( handle , port_profile , ucsm_ip ) except Exception as e : LOG . debug ( 'Received Port Profile delete exception %s' , e ) self . ucsm_db . add_port_profile_to_delete_table ( port_profile , ucsm_ip )
Calls method to delete Port Profile from UCS Manager . If exception is raised by UCSM then the PP is added to a DB table . The delete timer thread tried to delete all PPs added to this table when it wakes up .
37,568
def delete_all_config_for_vlan ( self , vlan_id , port_profile , trunk_vlans ) : ucsm_ips = list ( CONF . ml2_cisco_ucsm . ucsms ) for ucsm_ip in ucsm_ips : with self . ucsm_connect_disconnect ( ucsm_ip ) as handle : LOG . debug ( 'Deleting config for VLAN %d from UCSM %s' , vlan_id , ucsm_ip ) if ( port_profile ) : self . _delete_port_profile ( handle , port_profile , ucsm_ip ) ucsm = CONF . ml2_cisco_ucsm . ucsms [ ucsm_ip ] if ucsm . sp_template_list : self . _remove_vlan_from_all_sp_templates ( handle , vlan_id , ucsm_ip ) if ucsm . vnic_template_list : self . _remove_vlan_from_vnic_templates ( handle , vlan_id , ucsm_ip ) if not ( ucsm . sp_template_list and ucsm . vnic_template_list ) : self . _remove_vlan_from_all_service_profiles ( handle , vlan_id , ucsm_ip ) self . _delete_vlan_profile ( handle , vlan_id , ucsm_ip ) if trunk_vlans : for vlan_id in trunk_vlans : self . _delete_vlan_profile ( handle , vlan_id , ucsm_ip )
Top level method to delete all config for vlan_id .
37,569
def ucs_manager_disconnect ( self , handle , ucsm_ip ) : try : handle . Logout ( ) except Exception as e : raise cexc . UcsmDisconnectFailed ( ucsm_ip = ucsm_ip , exc = e )
Disconnects from the UCS Manager .
37,570
def add_events ( self , ** kwargs ) : event_q = kwargs . get ( 'event_queue' ) pri = kwargs . get ( 'priority' ) if not event_q or not pri : return try : event_type = 'server.failure.recovery' payload = { } timestamp = time . ctime ( ) data = ( event_type , payload ) event_q . put ( ( pri , timestamp , data ) ) LOG . debug ( 'Added failure recovery event to the queue.' ) except Exception as exc : LOG . exception ( 'Error: %(exc)s for event %(event)s' , { 'exc' : str ( exc ) , 'event' : event_type } ) raise exc
Add failure event into the queue .
37,571
def init_params ( self , protocol_interface , phy_interface ) : self . lldp_cfgd = False self . local_intf = protocol_interface self . phy_interface = phy_interface self . remote_evb_cfgd = False self . remote_evb_mode = None self . remote_mgmt_addr = None self . remote_system_desc = None self . remote_system_name = None self . remote_port = None self . remote_chassis_id_mac = None self . remote_port_id_mac = None self . local_evb_cfgd = False self . local_evb_mode = None self . local_mgmt_address = None self . local_system_desc = None self . local_system_name = None self . local_port = None self . local_chassis_id_mac = None self . local_port_id_mac = None self . db_retry_status = False self . topo_send_cnt = 0 self . bond_interface = None self . bond_member_ports = None
Initializing parameters .
37,572
def cmp_update_bond_intf ( self , bond_interface ) : if bond_interface != self . bond_interface : self . bond_interface = bond_interface self . bond_member_ports = sys_utils . get_member_ports ( bond_interface ) return True return False
Update the bond interface and its members .
37,573
def remote_evb_mode_uneq_store ( self , remote_evb_mode ) : if remote_evb_mode != self . remote_evb_mode : self . remote_evb_mode = remote_evb_mode return True return False
Saves the EVB mode if it is not the same as stored .
37,574
def remote_evb_cfgd_uneq_store ( self , remote_evb_cfgd ) : if remote_evb_cfgd != self . remote_evb_cfgd : self . remote_evb_cfgd = remote_evb_cfgd return True return False
This saves the EVB cfg if it is not the same as stored .
37,575
def remote_mgmt_addr_uneq_store ( self , remote_mgmt_addr ) : if remote_mgmt_addr != self . remote_mgmt_addr : self . remote_mgmt_addr = remote_mgmt_addr return True return False
This function saves the MGMT address if different from stored .
37,576
def remote_sys_desc_uneq_store ( self , remote_system_desc ) : if remote_system_desc != self . remote_system_desc : self . remote_system_desc = remote_system_desc return True return False
This function saves the system desc if different from stored .
37,577
def remote_sys_name_uneq_store ( self , remote_system_name ) : if remote_system_name != self . remote_system_name : self . remote_system_name = remote_system_name return True return False
This function saves the system name if different from stored .
37,578
def remote_port_uneq_store ( self , remote_port ) : if remote_port != self . remote_port : self . remote_port = remote_port return True return False
This function saves the port if different from stored .
37,579
def remote_chassis_id_mac_uneq_store ( self , remote_chassis_id_mac ) : if remote_chassis_id_mac != self . remote_chassis_id_mac : self . remote_chassis_id_mac = remote_chassis_id_mac return True return False
This function saves the Chassis MAC if different from stored .
37,580
def remote_port_id_mac_uneq_store ( self , remote_port_id_mac ) : if remote_port_id_mac != self . remote_port_id_mac : self . remote_port_id_mac = remote_port_id_mac return True return False
This function saves the port MAC if different from stored .
37,581
def get_lldp_status ( cls , intf ) : if intf not in cls . topo_intf_obj_dict : LOG . error ( "Interface %s not configured at all" , intf ) return False intf_obj = cls . topo_intf_obj_dict . get ( intf ) return intf_obj . get_lldp_status ( )
Retrieves the LLDP status .
37,582
def _init_cfg_interfaces ( self , cb , intf_list = None , all_intf = True ) : if not all_intf : self . intf_list = intf_list else : self . intf_list = sys_utils . get_all_run_phy_intf ( ) self . cb = cb self . intf_attr = { } self . cfg_lldp_interface_list ( self . intf_list )
Configure the interfaces during init time .
37,583
def cfg_intf ( self , protocol_interface , phy_interface = None ) : self . intf_list . append ( protocol_interface ) self . cfg_lldp_interface ( protocol_interface , phy_interface )
Called by application to add an interface to the list .
37,584
def create_attr_obj ( self , protocol_interface , phy_interface ) : self . intf_attr [ protocol_interface ] = TopoIntfAttr ( protocol_interface , phy_interface ) self . store_obj ( protocol_interface , self . intf_attr [ protocol_interface ] )
Creates the local interface attribute object and stores it .
37,585
def cmp_store_tlv_params ( self , intf , tlv_data ) : flag = False attr_obj = self . get_attr_obj ( intf ) remote_evb_mode = self . pub_lldp . get_remote_evb_mode ( tlv_data ) if attr_obj . remote_evb_mode_uneq_store ( remote_evb_mode ) : flag = True remote_evb_cfgd = self . pub_lldp . get_remote_evb_cfgd ( tlv_data ) if attr_obj . remote_evb_cfgd_uneq_store ( remote_evb_cfgd ) : flag = True remote_mgmt_addr = self . pub_lldp . get_remote_mgmt_addr ( tlv_data ) if attr_obj . remote_mgmt_addr_uneq_store ( remote_mgmt_addr ) : flag = True remote_sys_desc = self . pub_lldp . get_remote_sys_desc ( tlv_data ) if attr_obj . remote_sys_desc_uneq_store ( remote_sys_desc ) : flag = True remote_sys_name = self . pub_lldp . get_remote_sys_name ( tlv_data ) if attr_obj . remote_sys_name_uneq_store ( remote_sys_name ) : flag = True remote_port = self . pub_lldp . get_remote_port ( tlv_data ) if attr_obj . remote_port_uneq_store ( remote_port ) : flag = True remote_chassis_id_mac = self . pub_lldp . get_remote_chassis_id_mac ( tlv_data ) if attr_obj . remote_chassis_id_mac_uneq_store ( remote_chassis_id_mac ) : flag = True remote_port_id_mac = self . pub_lldp . get_remote_port_id_mac ( tlv_data ) if attr_obj . remote_port_id_mac_uneq_store ( remote_port_id_mac ) : flag = True return flag
Compare and store the received TLV .
37,586
def cfg_lldp_interface ( self , protocol_interface , phy_interface = None ) : if phy_interface is None : phy_interface = protocol_interface self . create_attr_obj ( protocol_interface , phy_interface ) ret = self . pub_lldp . enable_lldp ( protocol_interface ) attr_obj = self . get_attr_obj ( protocol_interface ) attr_obj . update_lldp_status ( ret )
Cfg LLDP on interface and create object .
37,587
def periodic_discovery_task ( self ) : try : self . _periodic_task_int ( ) except Exception as exc : LOG . error ( "Exception caught in periodic discovery task %s" , str ( exc ) )
Periodic task that checks the interface TLV attributes .
37,588
def _check_bond_interface_change ( self , phy_interface , attr_obj ) : bond_phy = sys_utils . get_bond_intf ( phy_interface ) if sys_utils . is_intf_bond ( phy_interface ) : bond_intf = phy_interface else : bond_intf = bond_phy bond_intf_change = attr_obj . cmp_update_bond_intf ( bond_intf ) return bond_intf_change
Check if there s any change in bond interface .
37,589
def _periodic_task_int ( self ) : for intf in self . intf_list : attr_obj = self . get_attr_obj ( intf ) status = attr_obj . get_lldp_status ( ) if not status : ret = self . pub_lldp . enable_lldp ( intf ) attr_obj . update_lldp_status ( ret ) continue bond_intf_change = self . _check_bond_interface_change ( attr_obj . get_phy_interface ( ) , attr_obj ) tlv_data = self . pub_lldp . get_lldp_tlv ( intf ) if self . cmp_store_tlv_params ( intf , tlv_data ) or ( attr_obj . get_db_retry_status ( ) or bond_intf_change or ( attr_obj . get_topo_disc_send_cnt ( ) > ( constants . TOPO_DISC_SEND_THRESHOLD ) ) ) : ret = self . cb ( intf , attr_obj ) status = not ret attr_obj . store_db_retry_status ( status ) attr_obj . reset_topo_disc_send_cnt ( ) else : attr_obj . incr_topo_disc_send_cnt ( )
Internal periodic discovery task routine to check TLV attributes .
37,590
def _get_cookie ( self , mgmt_ip , config , refresh = False ) : if mgmt_ip not in self . credentials : return None security_data = self . credentials [ mgmt_ip ] verify = security_data [ const . HTTPS_CERT_TUPLE ] if not verify : verify = security_data [ const . HTTPS_VERIFY_TUPLE ] if not refresh and security_data [ const . COOKIE_TUPLE ] : return security_data [ const . COOKIE_TUPLE ] , verify payload = { "aaaUser" : { "attributes" : { "name" : security_data [ const . UNAME_TUPLE ] , "pwd" : security_data [ const . PW_TUPLE ] } } } headers = { "Content-type" : "application/json" , "Accept" : "text/plain" } url = "{0}://{1}/api/aaaLogin.json" . format ( DEFAULT_SCHEME , mgmt_ip ) try : response = self . session . request ( 'POST' , url , data = jsonutils . dumps ( payload ) , headers = headers , verify = verify , timeout = self . timeout * 2 ) except Exception as e : raise cexc . NexusConnectFailed ( nexus_host = mgmt_ip , exc = e ) self . status = response . status_code if response . status_code == requests . codes . OK : cookie = response . headers . get ( 'Set-Cookie' ) security_data = ( security_data [ const . UNAME_TUPLE : const . COOKIE_TUPLE ] + ( cookie , ) ) self . credentials [ mgmt_ip ] = security_data return cookie , verify else : e = "REST API connect returned Error code: " e += str ( self . status ) raise cexc . NexusConnectFailed ( nexus_host = mgmt_ip , exc = e )
Performs authentication and retries cookie .
37,591
def _initialize_trunk_interfaces_to_none ( self , switch_ip , replay = True ) : try : switch_ifs = self . _mdriver . _get_switch_interfaces ( switch_ip , cfg_only = ( False if replay else True ) ) if not switch_ifs : LOG . debug ( "Skipping switch %s which has no configured " "interfaces" , switch_ip ) return self . _driver . initialize_all_switch_interfaces ( switch_ifs , switch_ip ) except Exception : with excutils . save_and_reraise_exception ( ) : LOG . warning ( "Unable to initialize interfaces to " "switch %(switch_ip)s" , { 'switch_ip' : switch_ip } ) self . _mdriver . register_switch_as_inactive ( switch_ip , 'replay init_interface' ) if self . _mdriver . is_replay_enabled ( ) : return
Initialize all nexus interfaces to trunk allowed none .
37,592
def replay_config ( self , switch_ip ) : LOG . debug ( "Replaying config for switch ip %(switch_ip)s" , { 'switch_ip' : switch_ip } ) try : self . _initialize_trunk_interfaces_to_none ( switch_ip ) except Exception : return nve_bindings = nxos_db . get_nve_switch_bindings ( switch_ip ) if ( len ( nve_bindings ) > 0 and cfg . CONF . ml2_cisco . vxlan_global_config ) : LOG . debug ( "Nexus: Replay NVE Interface" ) loopback = self . _mdriver . get_nve_loopback ( switch_ip ) self . _driver . enable_vxlan_feature ( switch_ip , const . NVE_INT_NUM , loopback ) for x in nve_bindings : try : self . _driver . create_nve_member ( switch_ip , const . NVE_INT_NUM , x . vni , x . mcast_group ) except Exception as e : LOG . error ( "Failed to configure nve_member for " "switch %(switch_ip)s, vni %(vni)s" "Reason:%(reason)s " , { 'switch_ip' : switch_ip , 'vni' : x . vni , 'reason' : e } ) self . _mdriver . register_switch_as_inactive ( switch_ip , 'replay create_nve_member' ) return try : port_bindings = nxos_db . get_nexusport_switch_bindings ( switch_ip ) except excep . NexusPortBindingNotFound : LOG . warning ( "No port entries found for switch ip " "%(switch_ip)s during replay." , { 'switch_ip' : switch_ip } ) return try : self . _mdriver . configure_switch_entries ( switch_ip , port_bindings ) except Exception as e : LOG . error ( "Unexpected exception while replaying " "entries for switch %(switch_ip)s, Reason:%(reason)s " , { 'switch_ip' : switch_ip , 'reason' : e } ) self . _mdriver . register_switch_as_inactive ( switch_ip , 'replay switch_entries' )
Sends pending config data in OpenStack to Nexus .
37,593
def check_connections ( self ) : switch_connections = self . _mdriver . get_all_switch_ips ( ) for switch_ip in switch_connections : state = self . _mdriver . get_switch_ip_and_active_state ( switch_ip ) config_failure = self . _mdriver . get_switch_replay_failure ( const . FAIL_CONFIG , switch_ip ) contact_failure = self . _mdriver . get_switch_replay_failure ( const . FAIL_CONTACT , switch_ip ) LOG . debug ( "check_connections() thread %(thid)d, switch " "%(switch_ip)s state %(state)s " "contact_failure %(contact_failure)d " "config_failure %(config_failure)d " , { 'thid' : threading . current_thread ( ) . ident , 'switch_ip' : switch_ip , 'state' : state , 'contact_failure' : contact_failure , 'config_failure' : config_failure } ) try : nexus_type = self . _driver . get_nexus_type ( switch_ip ) except Exception : if state != const . SWITCH_INACTIVE : LOG . error ( "Lost connection to switch ip " "%(switch_ip)s" , { 'switch_ip' : switch_ip } ) self . _mdriver . set_switch_ip_and_active_state ( switch_ip , const . SWITCH_INACTIVE ) else : self . _mdriver . incr_switch_replay_failure ( const . FAIL_CONTACT , switch_ip ) else : if state == const . SWITCH_RESTORE_S2 : try : self . _mdriver . configure_next_batch_of_vlans ( switch_ip ) except Exception as e : LOG . error ( "Unexpected exception while replaying " "entries for switch %(switch_ip)s, " "Reason:%(reason)s " , { 'switch_ip' : switch_ip , 'reason' : e } ) self . _mdriver . register_switch_as_inactive ( switch_ip , 'replay next_vlan_batch' ) continue if state == const . SWITCH_INACTIVE : self . _configure_nexus_type ( switch_ip , nexus_type ) LOG . info ( "Re-established connection to switch " "ip %(switch_ip)s" , { 'switch_ip' : switch_ip } ) self . _mdriver . set_switch_ip_and_active_state ( switch_ip , const . SWITCH_RESTORE_S1 ) self . replay_config ( switch_ip ) if self . _mdriver . get_switch_ip_and_active_state ( switch_ip ) == const . SWITCH_INACTIVE : self . _mdriver . incr_switch_replay_failure ( const . FAIL_CONFIG , switch_ip ) LOG . warning ( "Replay config failed for " "ip %(switch_ip)s" , { 'switch_ip' : switch_ip } ) else : self . _mdriver . reset_switch_replay_failure ( const . FAIL_CONFIG , switch_ip ) self . _mdriver . reset_switch_replay_failure ( const . FAIL_CONTACT , switch_ip ) LOG . info ( "Replay config successful for " "ip %(switch_ip)s" , { 'switch_ip' : switch_ip } )
Check connection between OpenStack to Nexus device .
37,594
def _pop_vlan_range ( self , switch_ip , size ) : vlan_range = self . _get_switch_vlan_range ( switch_ip ) sized_range = '' fr = 0 to = 0 while size > 0 and vlan_range : vlan_id , vni = vlan_range . pop ( 0 ) size -= 1 if fr == 0 and to == 0 : fr = vlan_id to = vlan_id else : diff = vlan_id - to if diff == 1 : to = vlan_id else : if fr == to : sized_range += str ( to ) + ',' else : sized_range += str ( fr ) + '-' sized_range += str ( to ) + ',' fr = vlan_id to = vlan_id if fr != 0 : if fr == to : sized_range += str ( to ) else : sized_range += str ( fr ) + '-' sized_range += str ( to ) self . _save_switch_vlan_range ( switch_ip , vlan_range ) return sized_range
Extract a specific number of vlans from storage .
37,595
def get_all_switch_ips ( self ) : switch_connections = [ ] try : bindings = nxos_db . get_reserved_switch_binding ( ) except excep . NexusPortBindingNotFound : LOG . error ( "No switch bindings in the port data base" ) bindings = [ ] for switch in bindings : switch_connections . append ( switch . switch_ip ) return switch_connections
Using reserved switch binding get all switch ips .
37,596
def _get_baremetal_switch_info ( self , link_info ) : try : switch_info = link_info [ 'switch_info' ] if not isinstance ( switch_info , dict ) : switch_info = jsonutils . loads ( switch_info ) except Exception as e : LOG . error ( "switch_info can't be decoded: %(exp)s" , { "exp" : e } ) switch_info = { } return switch_info
Get switch_info dictionary from context .
37,597
def _supported_baremetal_transaction ( self , context ) : port = context . current if self . trunk . is_trunk_subport_baremetal ( port ) : return self . _baremetal_set_binding ( context ) if not nexus_help . is_baremetal ( port ) : return False if bc . portbindings . PROFILE not in port : return False profile = port [ bc . portbindings . PROFILE ] if 'local_link_information' not in profile : return False all_link_info = profile [ 'local_link_information' ] selected = False for link_info in all_link_info : if 'port_id' not in link_info : return False switch_info = self . _get_baremetal_switch_info ( link_info ) if 'switch_ip' in switch_info : switch_ip = switch_info [ 'switch_ip' ] else : return False if self . _switch_defined ( switch_ip ) : selected = True else : LOG . warning ( "Skip switch %s. Not configured " "in ini file" % switch_ip ) if not selected : return False selected = self . _baremetal_set_binding ( context , all_link_info ) if selected : self . _init_baremetal_trunk_interfaces ( context . current , context . top_bound_segment ) if self . trunk . is_trunk_parentport ( port ) : self . trunk . update_subports ( port ) return selected
Verify transaction is complete and for us .
37,598
def _get_baremetal_switches ( self , port ) : all_switches = set ( ) active_switches = set ( ) all_link_info = port [ bc . portbindings . PROFILE ] [ 'local_link_information' ] for link_info in all_link_info : switch_info = self . _get_baremetal_switch_info ( link_info ) if not switch_info : continue switch_ip = switch_info [ 'switch_ip' ] if not self . _switch_defined ( switch_ip ) : continue all_switches . add ( switch_ip ) if self . is_switch_active ( switch_ip ) : active_switches . add ( switch_ip ) return list ( all_switches ) , list ( active_switches )
Get switch ip addresses from baremetal transaction .
37,599
def _get_baremetal_connections ( self , port , only_active_switch = False , from_segment = False ) : connections = [ ] is_native = False if self . trunk . is_trunk_subport ( port ) else True all_link_info = port [ bc . portbindings . PROFILE ] [ 'local_link_information' ] for link_info in all_link_info : intf_type , port = nexus_help . split_interface_name ( link_info [ 'port_id' ] ) switch_info = self . _get_baremetal_switch_info ( link_info ) if not switch_info : continue switch_ip = switch_info [ 'switch_ip' ] if not self . _switch_defined ( switch_ip ) : continue if ( only_active_switch and not self . is_switch_active ( switch_ip ) ) : continue ch_grp = 0 if not from_segment : try : reserved = nxos_db . get_switch_if_host_mappings ( switch_ip , nexus_help . format_interface_name ( intf_type , port ) ) if reserved [ 0 ] . ch_grp > 0 : ch_grp = reserved [ 0 ] . ch_grp intf_type , port = nexus_help . split_interface_name ( '' , ch_grp ) except excep . NexusHostMappingNotFound : pass connections . append ( ( switch_ip , intf_type , port , is_native , ch_grp ) ) return connections
Get switch ips and interfaces from baremetal transaction .