idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
38,100 | def delete_dcnm_in_nwk ( self , tenant_id , fw_dict , is_fw_virt = False ) : tenant_name = fw_dict . get ( 'tenant_name' ) ret = self . _delete_service_nwk ( tenant_id , tenant_name , 'in' ) if ret : res = fw_const . DCNM_IN_NETWORK_DEL_SUCCESS LOG . info ( "In Service network deleted for tenant %s" , tenant_id ) else : res = fw_const . DCNM_IN_NETWORK_DEL_FAIL LOG . info ( "In Service network deleted failed for tenant %s" , tenant_id ) self . update_fw_db_result ( tenant_id , dcnm_status = res ) return ret | Delete the DCNM In Network and store the result in DB . |
38,101 | def update_dcnm_in_part ( self , tenant_id , fw_dict , is_fw_virt = False ) : res = fw_const . DCNM_IN_PART_UPDATE_SUCCESS tenant_name = fw_dict . get ( 'tenant_name' ) ret = True try : self . _update_partition_in_create ( tenant_id , tenant_name ) except Exception as exc : LOG . error ( "Update of In Partition failed for tenant %(tenant)s" " Exception %(exc)s" , { 'tenant' : tenant_id , 'exc' : str ( exc ) } ) res = fw_const . DCNM_IN_PART_UPDATE_FAIL ret = False self . update_fw_db_result ( tenant_id , dcnm_status = res ) LOG . info ( "In partition updated with service ip addr" ) return ret | Update DCNM s in partition information . |
38,102 | def clear_dcnm_in_part ( self , tenant_id , fw_dict , is_fw_virt = False ) : res = fw_const . DCNM_IN_PART_UPDDEL_SUCCESS tenant_name = fw_dict . get ( 'tenant_name' ) ret = True try : self . _update_partition_in_delete ( tenant_name ) except Exception as exc : LOG . error ( "Clear of In Partition failed for tenant %(tenant)s" " , Exception %(exc)s" , { 'tenant' : tenant_id , 'exc' : str ( exc ) } ) res = fw_const . DCNM_IN_PART_UPDDEL_FAIL ret = False self . update_fw_db_result ( tenant_id , dcnm_status = res ) LOG . info ( "In partition cleared off service ip addr" ) return ret | Clear the DCNM in partition service information . |
38,103 | def create_dcnm_out_part ( self , tenant_id , fw_dict , is_fw_virt = False ) : res = fw_const . DCNM_OUT_PART_CREATE_SUCCESS tenant_name = fw_dict . get ( 'tenant_name' ) ret = True try : self . _create_out_partition ( tenant_id , tenant_name ) except Exception as exc : LOG . error ( "Create of Out Partition failed for tenant " "%(tenant)s ,Exception %(exc)s" , { 'tenant' : tenant_id , 'exc' : str ( exc ) } ) res = fw_const . DCNM_OUT_PART_CREATE_FAIL ret = False self . update_fw_db_result ( tenant_id , dcnm_status = res ) LOG . info ( "Out partition created" ) return ret | Create the DCNM OUT partition and update the result . |
38,104 | def delete_dcnm_out_part ( self , tenant_id , fw_dict , is_fw_virt = False ) : res = fw_const . DCNM_OUT_PART_DEL_SUCCESS tenant_name = fw_dict . get ( 'tenant_name' ) ret = True try : self . _delete_partition ( tenant_id , tenant_name ) except Exception as exc : LOG . error ( "deletion of Out Partition failed for tenant " "%(tenant)s, Exception %(exc)s" , { 'tenant' : tenant_id , 'exc' : str ( exc ) } ) res = fw_const . DCNM_OUT_PART_DEL_FAIL ret = False self . update_fw_db_result ( tenant_id , dcnm_status = res ) LOG . info ( "Out partition deleted" ) return ret | Delete the DCNM OUT partition and update the result . |
38,105 | def create_dcnm_out_nwk ( self , tenant_id , fw_dict , is_fw_virt = False ) : tenant_name = fw_dict . get ( 'tenant_name' ) ret = self . _create_service_nwk ( tenant_id , tenant_name , 'out' ) if ret : res = fw_const . DCNM_OUT_NETWORK_CREATE_SUCCESS LOG . info ( "out Service network created for tenant %s" , tenant_id ) else : res = fw_const . DCNM_OUT_NETWORK_CREATE_FAIL LOG . info ( "out Service network create failed for tenant %s" , tenant_id ) self . update_fw_db_result ( tenant_id , dcnm_status = res ) return ret | Create the DCNM OUT Network and update the result . |
38,106 | def delete_dcnm_out_nwk ( self , tenant_id , fw_dict , is_fw_virt = False ) : tenant_name = fw_dict . get ( 'tenant_name' ) ret = self . _delete_service_nwk ( tenant_id , tenant_name , 'out' ) if ret : res = fw_const . DCNM_OUT_NETWORK_DEL_SUCCESS LOG . info ( "out Service network deleted for tenant %s" , tenant_id ) else : res = fw_const . DCNM_OUT_NETWORK_DEL_FAIL LOG . info ( "out Service network deleted failed for tenant %s" , tenant_id ) self . update_fw_db_result ( tenant_id , dcnm_status = res ) return ret | Delete the DCNM OUT network and update the result . |
38,107 | def update_dcnm_out_part ( self , tenant_id , fw_dict , is_fw_virt = False ) : res = fw_const . DCNM_OUT_PART_UPDATE_SUCCESS tenant_name = fw_dict . get ( 'tenant_name' ) ret = True try : ret = self . _update_partition_out_create ( tenant_id , tenant_name ) if not ret : res = fw_const . DCNM_OUT_PART_UPDATE_FAIL except Exception as exc : LOG . error ( "Update of Out Partition failed for tenant " "%(tenant)s Exception %(exc)s" , { 'tenant' : tenant_id , 'exc' : str ( exc ) } ) res = fw_const . DCNM_OUT_PART_UPDATE_FAIL ret = False self . update_fw_db_result ( tenant_id , dcnm_status = res ) LOG . info ( "Out partition updated with service ip addr" ) return ret | Update DCNM OUT partition service node IP address and result . |
38,108 | def clear_dcnm_out_part ( self , tenant_id , fw_dict , is_fw_virt = False ) : res = fw_const . DCNM_OUT_PART_UPDDEL_SUCCESS self . update_fw_db_result ( tenant_id , dcnm_status = res ) LOG . info ( "Out partition cleared -noop- with service ip addr" ) return True | Clear DCNM out partition information . |
38,109 | def get_next_create_state ( self , state , ret ) : if ret : if state == fw_const . FABRIC_PREPARE_DONE_STATE : return state else : return state + 1 else : return state | Return the next create state from previous state . |
38,110 | def get_next_del_state ( self , state , ret ) : if ret : if state == fw_const . INIT_STATE : return state else : return state - 1 else : return state | Return the next delete state from previous state . |
38,111 | def get_next_state ( self , state , ret , oper ) : if oper == fw_const . FW_CR_OP : return self . get_next_create_state ( state , ret ) else : return self . get_next_del_state ( state , ret ) | Returns the next state for a create or delete operation . |
38,112 | def run_create_sm ( self , tenant_id , fw_dict , is_fw_virt ) : ret = True serv_obj = self . get_service_obj ( tenant_id ) state = serv_obj . get_state ( ) new_state = serv_obj . fixup_state ( fw_const . FW_CR_OP , state ) serv_obj . store_local_final_result ( fw_const . RESULT_FW_CREATE_INIT ) if state != new_state : state = new_state serv_obj . store_state ( state ) while ret : try : ret = self . fabric_fsm [ state ] [ 0 ] ( tenant_id , fw_dict , is_fw_virt = is_fw_virt ) except Exception as exc : LOG . error ( "Exception %(exc)s for state %(state)s" , { 'exc' : str ( exc ) , 'state' : fw_const . fw_state_fn_dict . get ( state ) } ) ret = False if ret : LOG . info ( "State %s return successfully" , fw_const . fw_state_fn_dict . get ( state ) ) state = self . get_next_state ( state , ret , fw_const . FW_CR_OP ) serv_obj . store_state ( state ) if state == fw_const . FABRIC_PREPARE_DONE_STATE : break if ret : serv_obj . store_local_final_result ( fw_const . RESULT_FW_CREATE_DONE ) return ret | Runs the create State Machine . |
38,113 | def run_delete_sm ( self , tenant_id , fw_dict , is_fw_virt ) : ret = True serv_obj = self . get_service_obj ( tenant_id ) state = serv_obj . get_state ( ) new_state = serv_obj . fixup_state ( fw_const . FW_DEL_OP , state ) serv_obj . store_local_final_result ( fw_const . RESULT_FW_DELETE_INIT ) if state != new_state : state = new_state serv_obj . store_state ( state ) while ret : try : ret = self . fabric_fsm [ state ] [ 1 ] ( tenant_id , fw_dict , is_fw_virt = is_fw_virt ) except Exception as exc : LOG . error ( "Exception %(exc)s for state %(state)s" , { 'exc' : str ( exc ) , 'state' : fw_const . fw_state_fn_del_dict . get ( state ) } ) ret = False if ret : LOG . info ( "State %s return successfully" , fw_const . fw_state_fn_del_dict . get ( state ) ) if state == fw_const . INIT_STATE : break state = self . get_next_state ( state , ret , fw_const . FW_DEL_OP ) serv_obj . store_state ( state ) return ret | Runs the delete State Machine . |
38,114 | def get_key_state ( self , status , state_dict ) : for key , val in state_dict . items ( ) : if val == status : return key | Returns the key associated with the dict . |
38,115 | def pop_fw_state ( self , compl_result , os_status , dcnm_status ) : res_list = compl_result . split ( '(' ) state_num = None if len ( res_list ) > 1 : state_num = int ( res_list [ 1 ] . split ( ')' ) [ 0 ] ) else : if res_list [ 0 ] == fw_const . RESULT_FW_CREATE_INIT : if os_status is None : state_num = fw_const . INIT_STATE elif res_list [ 0 ] == fw_const . RESULT_FW_CREATE_DONE : state_num = fw_const . FABRIC_PREPARE_DONE_STATE elif res_list [ 0 ] == fw_const . RESULT_FW_DELETE_INIT : if os_status == fw_const . OS_CREATE_SUCCESS and ( dcnm_status == fw_const . DCNM_CREATE_SUCCESS ) : state_num = fw_const . FABRIC_PREPARE_DONE_STATE return state_num | Populate the state information in the cache . |
38,116 | def pop_fw_local ( self , tenant_id , net_id , direc , node_ip ) : net = self . get_network ( net_id ) serv_obj = self . get_service_obj ( tenant_id ) serv_obj . update_fw_local_cache ( net_id , direc , node_ip ) if net is not None : net_dict = self . fill_dcnm_net_info ( tenant_id , direc , net . vlan , net . segmentation_id ) serv_obj . store_dcnm_net_dict ( net_dict , direc ) if direc == "in" : subnet = self . service_in_ip . get_subnet_by_netid ( net_id ) else : subnet = self . service_out_ip . get_subnet_by_netid ( net_id ) if subnet is not None : subnet_dict = self . fill_dcnm_subnet_info ( tenant_id , subnet , self . get_start_ip ( subnet ) , self . get_end_ip ( subnet ) , self . get_gateway ( subnet ) , self . get_secondary_gateway ( subnet ) , direc ) serv_obj . store_dcnm_subnet_dict ( subnet_dict , direc ) | Populate the local cache . |
38,117 | def populate_local_cache_tenant ( self , fw_id , fw_data ) : tenant_id = fw_data . get ( 'tenant_id' ) self . create_serv_obj ( tenant_id ) serv_obj = self . get_service_obj ( tenant_id ) serv_obj . create_fw_db ( fw_id , fw_data . get ( 'name' ) , tenant_id ) self . pop_fw_local ( tenant_id , fw_data . get ( 'in_network_id' ) , "in" , fw_data . get ( 'in_service_node_ip' ) ) self . pop_fw_local ( tenant_id , fw_data . get ( 'out_network_id' ) , "out" , fw_data . get ( 'out_service_node_ip' ) ) serv_obj . update_fw_local_result_str ( fw_data . get ( 'os_status' ) , fw_data . get ( 'dcnm_status' ) , fw_data . get ( 'device_status' ) ) compl_res = fw_data . get ( 'result' ) result = compl_res . split ( '(' ) [ 0 ] serv_obj . store_local_final_result ( result ) state = self . pop_fw_state ( compl_res , fw_data . get ( 'os_status' ) , fw_data . get ( 'dcnm_status' ) ) if state is None : LOG . error ( "Unable to get state complete result %(res)s" " OS status %(os)s, dcnm status %(dcnm)s" , { 'res' : compl_res , 'os' : fw_data . get ( 'os_status' ) , 'dcnm' : fw_data . get ( 'dcnm_status' ) } ) serv_obj . store_state ( state , popl_db = False ) if state == fw_const . FABRIC_PREPARE_DONE_STATE : serv_obj . set_fabric_create ( True ) router_id = fw_data . get ( 'router_id' ) rout_net_id = fw_data . get ( 'router_net_id' ) rout_subnet_id = fw_data . get ( 'router_subnet_id' ) serv_obj . update_fw_local_router ( rout_net_id , rout_subnet_id , router_id , None ) | Populate the cache for a given tenant . |
38,118 | def populate_local_cache ( self ) : fw_dict = self . get_all_fw_db ( ) for fw_id in fw_dict : LOG . info ( "Populating cache for FW %s" , fw_id ) fw_data = fw_dict [ fw_id ] self . populate_local_cache_tenant ( fw_id , fw_data ) | Populate the local cache from DB . |
38,119 | def delete_os_dummy_rtr_nwk ( self , rtr_id , net_id , subnet_id ) : subnet_lst = set ( ) subnet_lst . add ( subnet_id ) ret = self . os_helper . delete_intf_router ( None , None , rtr_id , subnet_lst ) if not ret : return ret return self . os_helper . delete_network_all_subnets ( net_id ) | Delete the dummy interface to the router . |
38,120 | def delete_os_nwk_db ( self , net_id , seg , vlan ) : if seg is not None : self . service_segs . release_segmentation_id ( seg ) if vlan is not None : self . service_vlans . release_segmentation_id ( vlan ) self . os_helper . delete_network_all_subnets ( net_id ) self . os_helper . delete_network_subname ( fw_const . IN_SERVICE_NWK ) self . delete_network_db ( net_id ) self . clear_fw_entry_by_netid ( net_id ) self . service_in_ip . release_subnet_by_netid ( net_id ) self . service_out_ip . release_subnet_by_netid ( net_id ) | Delete the Openstack Network from the database . |
38,121 | def correct_db_restart ( self ) : LOG . info ( "Checking consistency of DB" ) seg_netid_dict = self . service_segs . get_seg_netid_src ( fw_const . FW_CONST ) vlan_netid_dict = self . service_vlans . get_seg_netid_src ( fw_const . FW_CONST ) for netid in seg_netid_dict : net = self . get_network ( netid ) fw_net = self . get_fw_by_netid ( netid ) if not net or not fw_net : if netid in vlan_netid_dict : vlan_net = vlan_netid_dict [ netid ] else : vlan_net = None self . delete_os_nwk_db ( netid , seg_netid_dict [ netid ] , vlan_net ) LOG . info ( "Allocated segment for net %s not in DB " "returning" , net ) return for netid in vlan_netid_dict : net = self . get_network ( netid ) fw_net = self . get_fw_by_netid ( netid ) if not net or not fw_net : if netid in seg_netid_dict : vlan_net = seg_netid_dict [ netid ] else : vlan_net = None self . delete_os_nwk_db ( netid , vlan_net , vlan_netid_dict [ netid ] ) LOG . info ( "Allocated vlan for net %s not in DB returning" , net ) return self . service_in_ip . release_subnet_no_netid ( ) self . service_out_ip . release_subnet_no_netid ( ) fw_dict = self . get_all_fw_db ( ) for fw_id in fw_dict : rtr_nwk = fw_id [ 0 : 4 ] + fw_const . DUMMY_SERVICE_NWK + ( fw_id [ len ( fw_id ) - 4 : ] ) net_list = self . os_helper . get_network_by_name ( rtr_nwk ) for net in net_list : net_db_item = self . get_network ( net . get ( 'id' ) ) if not net_db_item : self . os_helper . delete_network_all_subnets ( net . get ( 'id' ) ) LOG . info ( "Router Network %s not in DB, returning" , net . get ( 'id' ) ) return rtr_name = fw_id [ 0 : 4 ] + fw_const . DUMMY_SERVICE_RTR + ( fw_id [ len ( fw_id ) - 4 : ] ) rtr_list = self . os_helper . get_rtr_by_name ( rtr_name ) for rtr in rtr_list : fw_db_item = self . get_fw_by_rtrid ( rtr . get ( 'id' ) ) if not fw_db_item : if not net_list : LOG . error ( "net_list len is 0, router net not " "found" ) return fw_type = fw_dict [ fw_id ] . get ( 'fw_type' ) if fw_type == fw_const . FW_TENANT_EDGE : rtr_net = net_list [ 0 ] rtr_subnet_lt = ( self . os_helper . get_subnets_for_net ( rtr_net ) ) if rtr_subnet_lt is None : LOG . error ( "router subnet not found for " "net %s" , rtr_net ) return rtr_subnet_id = rtr_subnet_lt [ 0 ] . get ( 'id' ) LOG . info ( "Deleted dummy router network %s" , rtr . get ( 'id' ) ) ret = self . delete_os_dummy_rtr_nwk ( rtr . get ( 'id' ) , rtr_net . get ( 'id' ) , rtr_subnet_id ) return ret LOG . info ( "Done Checking consistency of DB, no issues" ) | Ensure DB is consistent after unexpected restarts . |
38,122 | def _prepare_fabric_fw_internal ( self , tenant_id , fw_dict , is_fw_virt , result ) : if not self . auto_nwk_create : LOG . info ( "Auto network creation disabled" ) return False try : tenant_name = fw_dict . get ( 'tenant_name' ) fw_id = fw_dict . get ( 'fw_id' ) fw_name = fw_dict . get ( 'fw_name' ) if tenant_id in self . service_attr and ( result == fw_const . RESULT_FW_CREATE_DONE ) : LOG . error ( "Fabric already prepared for tenant %(tenant)s," " %(name)s" , { 'tenant' : tenant_id , 'name' : tenant_name } ) return True if tenant_id not in self . service_attr : self . create_serv_obj ( tenant_id ) self . service_attr [ tenant_id ] . create_fw_db ( fw_id , fw_name , tenant_id ) ret = self . run_create_sm ( tenant_id , fw_dict , is_fw_virt ) if ret : LOG . info ( "SM create returned True for Tenant Name " "%(tenant)s FW %(fw)s" , { 'tenant' : tenant_name , 'fw' : fw_name } ) self . service_attr [ tenant_id ] . set_fabric_create ( True ) else : LOG . error ( "SM create returned False for Tenant Name " "%(tenant)s FW %(fw)s" , { 'tenant' : tenant_name , 'fw' : fw_name } ) except Exception as exc : LOG . error ( "Exception raised in create fabric int %s" , str ( exc ) ) return False return ret | Internal routine to prepare the fabric . |
38,123 | def prepare_fabric_fw ( self , tenant_id , fw_dict , is_fw_virt , result ) : try : with self . mutex_lock : ret = self . _prepare_fabric_fw_internal ( tenant_id , fw_dict , is_fw_virt , result ) except Exception as exc : LOG . error ( "Exception raised in create fabric %s" , str ( exc ) ) return False return ret | Top level routine to prepare the fabric . |
38,124 | def delete_fabric_fw_internal ( self , tenant_id , fw_dict , is_fw_virt , result ) : if not self . auto_nwk_create : LOG . info ( "Auto network creation disabled" ) return False try : tenant_name = fw_dict . get ( 'tenant_name' ) fw_name = fw_dict . get ( 'fw_name' ) if tenant_id not in self . service_attr : LOG . error ( "Service obj not created for tenant %s" , tenant_name ) return False if result == fw_const . RESULT_FW_DELETE_DONE : LOG . error ( "Fabric for tenant %s already deleted" , tenant_id ) return True ret = self . run_delete_sm ( tenant_id , fw_dict , is_fw_virt ) self . service_attr [ tenant_id ] . set_fabric_create ( False ) if ret : LOG . info ( "Delete SM completed successfully for tenant" "%(tenant)s FW %(fw)s" , { 'tenant' : tenant_name , 'fw' : fw_name } ) self . service_attr [ tenant_id ] . destroy_local_fw_db ( ) self . delete_serv_obj ( tenant_id ) else : LOG . error ( "Delete SM failed for tenant" "%(tenant)s FW %(fw)s" , { 'tenant' : tenant_name , 'fw' : fw_name } ) except Exception as exc : LOG . error ( "Exception raised in delete fabric int %s" , str ( exc ) ) return False return ret | Internal routine to delete the fabric configuration . |
38,125 | def delete_fabric_fw ( self , tenant_id , fw_dict , is_fw_virt , result ) : try : with self . mutex_lock : ret = self . delete_fabric_fw_internal ( tenant_id , fw_dict , is_fw_virt , result ) except Exception as exc : LOG . error ( "Exception raised in delete fabric %s" , str ( exc ) ) return False return ret | Top level routine to unconfigure the fabric . |
38,126 | def retry_failure_internal ( self , tenant_id , tenant_name , fw_data , is_fw_virt , result ) : if not self . auto_nwk_create : LOG . info ( "Auto network creation disabled" ) return False try : if tenant_id not in self . service_attr : LOG . error ( "Tenant Obj not created" ) return False if result == fw_const . RESULT_FW_CREATE_INIT : ret = self . run_create_sm ( tenant_id , fw_data , is_fw_virt ) else : if result == fw_const . RESULT_FW_DELETE_INIT : ret = self . run_delete_sm ( tenant_id , fw_data , is_fw_virt ) else : LOG . error ( "Unknown state in retry" ) return False self . service_attr [ tenant_id ] . set_fabric_create ( ret ) except Exception as exc : LOG . error ( "Exception raised in create fabric int %s" , str ( exc ) ) return False return ret | Internal routine to retry the failed cases . |
38,127 | def retry_failure ( self , tenant_id , tenant_name , fw_data , is_fw_virt , result ) : try : with self . mutex_lock : ret = self . retry_failure_internal ( tenant_id , tenant_name , fw_data , is_fw_virt , result ) except Exception as exc : LOG . error ( "Exception raised in create fabric %s" , str ( exc ) ) return False return ret | Top level retry failure routine . |
38,128 | def verify_resource_dict ( res_dict , is_create , attr_info ) : if ( ( bc . NEUTRON_VERSION >= bc . NEUTRON_NEWTON_VERSION ) and 'tenant_id' in res_dict ) : res_dict [ 'project_id' ] = res_dict [ 'tenant_id' ] if is_create : for attr , attr_vals in six . iteritems ( attr_info ) : if attr_vals [ 'allow_post' ] : if 'default' not in attr_vals and attr not in res_dict : msg = _ ( "Failed to parse request. Required attribute '%s' " "not specified" ) % attr raise webob . exc . HTTPBadRequest ( msg ) res_dict [ attr ] = res_dict . get ( attr , attr_vals . get ( 'default' ) ) else : if attr in res_dict : msg = _ ( "Attribute '%s' not allowed in POST" ) % attr raise webob . exc . HTTPBadRequest ( msg ) else : for attr , attr_vals in six . iteritems ( attr_info ) : if attr in res_dict and not attr_vals [ 'allow_put' ] : msg = _ ( "Cannot update read-only attribute %s" ) % attr raise webob . exc . HTTPBadRequest ( msg ) for attr , attr_vals in six . iteritems ( attr_info ) : if ( attr not in res_dict or res_dict [ attr ] is bc . constants . ATTR_NOT_SPECIFIED ) : continue if 'convert_to' in attr_vals : res_dict [ attr ] = attr_vals [ 'convert_to' ] ( res_dict [ attr ] ) if 'validate' not in attr_vals : continue for rule in attr_vals [ 'validate' ] : _ensure_format ( rule , attr , res_dict ) res = bc . validators [ rule ] ( res_dict [ attr ] , attr_vals [ 'validate' ] [ rule ] ) if res : msg_dict = dict ( attr = attr , reason = res ) msg = ( _ ( "Invalid input for %(attr)s. Reason: %(reason)s." ) % msg_dict ) raise webob . exc . HTTPBadRequest ( msg ) return res_dict | Verifies required attributes are in resource dictionary res_dict . |
38,129 | def uuidify ( val ) : if uuidutils . is_uuid_like ( val ) : return val else : try : int_val = int ( val , 16 ) except ValueError : with excutils . save_and_reraise_exception ( ) : LOG . error ( "Invalid UUID format %s. Please provide an " "integer in decimal (0-9) or hex (0-9a-e) " "format" , val ) res = str ( int_val ) num = 12 - len ( res ) return "00000000-0000-0000-0000-" + "0" * num + res | Takes an integer and transforms it to a UUID format . |
38,130 | def _ensure_format ( rule , attribute , res_dict ) : if rule == 'type:uuid' or ( rule == 'type:uuid_or_none' and res_dict [ attribute ] ) : res_dict [ attribute ] = uuidify ( res_dict [ attribute ] ) elif rule == 'type:uuid_list' : if not res_dict [ attribute ] : res_dict [ attribute ] = [ ] else : temp_list = res_dict [ attribute ] . split ( ':' ) res_dict [ attribute ] = [ ] for item in temp_list : res_dict [ attribute ] . append = uuidify ( item ) elif rule == 'type:string_or_none' and res_dict [ attribute ] == "" : res_dict [ attribute ] = None | Verifies that attribute in res_dict is properly formatted . |
38,131 | def obtain_hosting_device_credentials_from_config ( ) : cred_dict = get_specific_config ( 'cisco_hosting_device_credential' ) attr_info = { 'name' : { 'allow_post' : True , 'allow_put' : True , 'validate' : { 'type:string' : None } , 'is_visible' : True , 'default' : '' } , 'description' : { 'allow_post' : True , 'allow_put' : True , 'validate' : { 'type:string' : None } , 'is_visible' : True , 'default' : '' } , 'user_name' : { 'allow_post' : True , 'allow_put' : True , 'validate' : { 'type:string' : None } , 'is_visible' : True , 'default' : '' } , 'password' : { 'allow_post' : True , 'allow_put' : True , 'validate' : { 'type:string' : None } , 'is_visible' : True , 'default' : '' } , 'type' : { 'allow_post' : True , 'allow_put' : True , 'validate' : { 'type:string' : None } , 'is_visible' : True , 'default' : '' } } credentials = { } for cred_uuid , kv_dict in cred_dict . items ( ) : cred_uuid = uuidify ( cred_uuid ) verify_resource_dict ( kv_dict , True , attr_info ) credentials [ cred_uuid ] = kv_dict return credentials | Obtains credentials from config file and stores them in memory . To be called before hosting device templates defined in the config file are created . |
38,132 | def get_routertypes ( self , context , filters = None , fields = None , sorts = None , limit = None , marker = None , page_reverse = False ) : pass | Lists defined router types . |
38,133 | def has_role ( self , role ) : return self . roles and any ( [ re . search ( role , our_role , re . I ) for our_role in self . roles ] ) | Check whether the Launch Paramters set the role . |
38,134 | def username ( self , default = None ) : if self . lis_person_name_given : return self . lis_person_name_given elif self . lis_person_name_family : return self . lis_person_name_family elif self . lis_person_name_full : return self . lis_person_name_full else : return default | Return the full given or family name if set . |
38,135 | def build_return_url ( self ) : if not self . launch_presentation_return_url : return None lti_message_fields = [ 'lti_errormsg' , 'lti_errorlog' , 'lti_msg' , 'lti_log' ] messages = dict ( [ ( key , getattr ( self , key ) ) for key in lti_message_fields if getattr ( self , key , None ) ] ) original = urlsplit ( self . launch_presentation_return_url ) combined = messages . copy ( ) combined . update ( dict ( parse_qsl ( original . query ) ) ) combined_query = urlencode ( combined ) return urlunsplit ( ( original . scheme , original . netloc , original . path , combined_query , original . fragment ) ) | If the Tool Consumer sent a return URL add any set messages to the URL . |
38,136 | def success_redirect ( self , msg = '' , log = '' ) : from django . shortcuts import redirect self . lti_msg = msg self . lti_log = log return redirect ( self . build_return_url ( ) ) | Shortcut for redirecting Django view to LTI Consumer with messages |
38,137 | def error_redirect ( self , errormsg = '' , errorlog = '' ) : from django . shortcuts import redirect self . lti_errormsg = errormsg self . lti_errorlog = errorlog return redirect ( self . build_return_url ( ) ) | Shortcut for redirecting Django view to LTI Consumer with errors |
38,138 | def _notify_thing_lid_change ( self , from_lid , to_lid ) : try : with self . __private_things : self . __private_things [ to_lid ] = self . __private_things . pop ( from_lid ) except KeyError : logger . warning ( 'Thing %s renamed (to %s), but not in private lookup table' , from_lid , to_lid ) else : try : with self . __new_things : self . __new_things [ to_lid ] = self . __new_things . pop ( from_lid ) except KeyError : pass | Used by Thing instances to indicate that a rename operation has happened |
38,139 | def register_catchall_feeddata ( self , callback , callback_parsed = None ) : if callback_parsed : callback = self . _get_parsed_feed_callback ( callback_parsed , callback ) return self . __client . register_callback_feeddata ( callback ) | Registers a callback that is called for all feeddata your Thing receives |
38,140 | def register_catchall_controlreq ( self , callback , callback_parsed = None ) : if callback_parsed : callback = self . _get_parsed_control_callback ( callback_parsed , callback ) return self . __client . register_callback_controlreq ( callback ) | Registers a callback that is called for all control requests received by your Thing |
38,141 | def register_callback_duplicate ( self , func , serialised = True ) : self . __client . register_callback_duplicate ( partial ( self . __callback_payload_only , func ) , serialised = serialised ) | Register a callback for resource creation but where the resource already exists in Iotic Space . In this case the existing reference is passed to you . If serialised is not set the callbacks might arrive in a different order to they were requested . |
38,142 | def register_callback_renamed ( self , func , serialised = True ) : self . __client . register_callback_renamed ( partial ( self . __callback_payload_only , func ) , serialised = serialised ) | Register a callback for resource rename . This will be called when any resource is renamed within your agent . If serialised is not set the callbacks might arrive in a different order to they were requested . |
38,143 | def register_callback_deleted ( self , func , serialised = True ) : self . __client . register_callback_deleted ( partial ( self . __callback_payload_only , func ) , serialised = serialised ) | Register a callback for resource deletion . This will be called when any resource is deleted within your agent . If serialised is not set the callbacks might arrive in a different order to they were requested . |
38,144 | def register_callback_reassigned ( self , func , serialised = True ) : self . __client . register_callback_reassigned ( partial ( self . __callback_payload_only , func ) , serialised ) | Register a callback for resource reassignment . This will be called when any resource is reassigned to or from your agent . If serialised is not set the callbacks might arrive in a different order to they were requested . |
38,145 | def simulate_feeddata ( self , feedid , data , mime = None , time = None ) : self . __client . simulate_feeddata ( feedid , data , mime , time ) | Simulate the last feeddata received for given feedid Calls the registered callback for the feed with the last recieved feed data . Allows you to test your code without having to wait for the remote thing to share again . |
38,146 | def confirm_tell ( self , data , success ) : logger . info ( "confirm_tell(success=%s) [lid=\"%s\",pid=\"%s\"]" , success , data [ P_ENTITY_LID ] , data [ P_LID ] ) evt = self . _request_point_confirm_tell ( R_CONTROL , data [ P_ENTITY_LID ] , data [ P_LID ] , success , data [ 'requestId' ] ) self . _wait_and_except_if_failed ( evt ) | Confirm that you ve done as you were told . Call this from your control callback to confirm action . Used when you are advertising a control and you want to tell the remote requestor that you have done what they asked you to . |
38,147 | def save_config ( self ) : self . __config . set ( 'agent' , 'seqnum' , self . __client . get_seqnum ( ) ) self . __config . set ( 'agent' , 'lang' , self . __client . default_lang ) self . __config . save ( ) | Save the config update the seqnum & default language |
38,148 | def _get_point_data_handler_for ( self , point ) : with self . __point_data_handlers : try : return self . __point_data_handlers [ point ] except KeyError : return self . __point_data_handlers . setdefault ( point , PointDataObjectHandler ( point , self ) ) | Used by point instances and data callbacks |
38,149 | def _wait_and_except_if_failed ( self , event , timeout = None ) : event . wait ( timeout or self . __sync_timeout ) self . _except_if_failed ( event ) | Combines waiting for event and call to _except_if_failed . If timeout is not specified the configured sync_timeout is used . |
38,150 | def _except_if_failed ( cls , event ) : if event . success is None : raise IOTSyncTimeout ( 'Requested timed out' , event ) if not event . success : msg = "Request failed, unknown error" if isinstance ( event . payload , Mapping ) : if P_MESSAGE in event . payload : msg = event . payload [ P_MESSAGE ] try : exc_class = cls . __exception_mapping [ event . payload [ P_CODE ] ] except KeyError : pass else : raise exc_class ( msg , event ) raise IOTException ( msg , event ) | Raises an IOTException from the given event if it was not successful . Assumes timeout success flag on event has not been set yet . |
38,151 | def list ( self , all_my_agents = False , limit = 500 , offset = 0 ) : logger . info ( "list(all_my_agents=%s, limit=%s, offset=%s)" , all_my_agents , limit , offset ) if all_my_agents : evt = self . _request_entity_list_all ( limit = limit , offset = offset ) else : evt = self . _request_entity_list ( limit = limit , offset = offset ) self . _wait_and_except_if_failed ( evt ) return evt . payload [ 'entities' ] | List all the things created by this client on this or all your agents |
38,152 | def get_thing ( self , lid ) : with self . __new_things : try : return self . __new_things . pop ( lid ) except KeyError as ex : raise_from ( KeyError ( 'Thing %s not know as new' % lid ) , ex ) | Get the details of a newly created Thing . This only applies to asynchronous creation of Things and the new Thing instance can only be retrieved once . |
38,153 | def delete_thing ( self , lid ) : logger . info ( "delete_thing(lid=\"%s\")" , lid ) evt = self . delete_thing_async ( lid ) self . _wait_and_except_if_failed ( evt ) | Delete a Thing |
38,154 | def from_post_request ( post_request ) : request = OutcomeRequest ( ) request . post_request = post_request request . process_xml ( post_request . data ) return request | Convenience method for creating a new OutcomeRequest from a request object . |
38,155 | def post_outcome_request ( self ) : if not self . has_required_attributes ( ) : raise InvalidLTIConfigError ( 'OutcomeRequest does not have all required attributes' ) consumer = oauth2 . Consumer ( key = self . consumer_key , secret = self . consumer_secret ) client = oauth2 . Client ( consumer ) monkey_patch_headers = True monkey_patch_function = None if monkey_patch_headers : import httplib2 http = httplib2 . Http normalize = http . _normalize_headers def my_normalize ( self , headers ) : print ( "My Normalize" , headers ) ret = normalize ( self , headers ) if 'authorization' in ret : ret [ 'Authorization' ] = ret . pop ( 'authorization' ) print ( "My Normalize" , ret ) return ret http . _normalize_headers = my_normalize monkey_patch_function = normalize response , content = client . request ( self . lis_outcome_service_url , 'POST' , body = self . generate_request_xml ( ) , headers = { 'Content-Type' : 'application/xml' } ) if monkey_patch_headers and monkey_patch_function : import httplib2 http = httplib2 . Http http . _normalize_headers = monkey_patch_function self . outcome_response = OutcomeResponse . from_post_response ( response , content ) return self . outcome_response | POST an OAuth signed request to the Tool Consumer . |
38,156 | def process_xml ( self , xml ) : root = objectify . fromstring ( xml ) self . message_identifier = str ( root . imsx_POXHeader . imsx_POXRequestHeaderInfo . imsx_messageIdentifier ) try : result = root . imsx_POXBody . replaceResultRequest self . operation = REPLACE_REQUEST self . lis_result_sourcedid = result . resultRecord . sourcedGUID . sourcedId self . score = str ( result . resultRecord . result . resultScore . textString ) except : pass try : result = root . imsx_POXBody . deleteResultRequest self . operation = DELETE_REQUEST self . lis_result_sourcedid = result . resultRecord . sourcedGUID . sourcedId except : pass try : result = root . imsx_POXBody . readResultRequest self . operation = READ_REQUEST self . lis_result_sourcedid = result . resultRecord . sourcedGUID . sourcedId except : pass | Parse Outcome Request data from XML . |
38,157 | def setup_logging ( self ) : logging . getLogger ( 'amqp' ) . setLevel ( str_to_logging ( self . get ( 'logging' , 'amqp' ) ) ) logging . getLogger ( 'rdflib' ) . setLevel ( str_to_logging ( self . get ( 'logging' , 'rdflib' ) ) ) | Setup logging module based on known modules in the config file |
38,158 | def save ( self , filename = None ) : if self . __fname is None and filename is None : raise ValueError ( 'Config loaded from string, no filename specified' ) conf = self . __config cpa = dict_to_cp ( conf ) with open ( self . __fname if filename is None else filename , 'w' ) as f : cpa . write ( f ) | Write config to file . |
38,159 | def get ( self , section , val ) : val = val . lower ( ) if section in self . __config : if val in self . __config [ section ] : return self . __config [ section ] [ val ] if section in self . __defaults : if val in self . __defaults [ section ] : return self . __defaults [ section ] [ val ] return None | Get a setting or the default |
38,160 | def set ( self , section , val , data ) : val = val . lower ( ) if section in self . __config : self . __config [ section ] [ val ] = data | Add a setting to the config |
38,161 | def update ( self , section , val , data ) : k = self . get ( section , val ) if data is not None and k != data : self . set ( section , val , data ) | Add a setting to the config but if same as default or None then no action . This saves the . save writing the defaults |
38,162 | def get_location ( self ) : lat = None lon = None for _ , _ , o in self . _graph . triples ( ( None , GEO_NS . lat , None ) ) : lat = float ( o ) break for _ , _ , o in self . _graph . triples ( ( None , GEO_NS . long , None ) ) : lon = float ( o ) break return lat , lon | Gets the current geo location of your Thing |
38,163 | def start ( self ) : if not ( self . __recv_thread or self . __send_thread ) : self . __end . clear ( ) self . __send_ready . clear ( ) self . __recv_ready . clear ( ) timeout = self . __socket_timeout + 1 ignore_exc = self . __startup_ignore_exc self . __send_exc_clear ( ) self . __recv_exc_clear ( ) self . __send_thread = Thread ( target = self . __send_run , name = 'amqplink_send' ) self . __send_thread . start ( ) start_time = monotonic ( ) success = False while not ( success or ( not ignore_exc and self . __send_exc ) or monotonic ( ) - start_time > timeout ) : success = self . __send_ready . wait ( .25 ) if success : self . __recv_thread = Thread ( target = self . __recv_run , name = 'amqplink_recv' ) self . __recv_thread . start ( ) start_time = monotonic ( ) success = False while not ( success or ( not ignore_exc and self . __recv_exc ) or monotonic ( ) - start_time >= timeout ) : success = self . __recv_ready . wait ( .25 ) if not success : logger . warning ( "AmqpLink Failed to start. Giving up." ) self . stop ( ) if self . __recv_exc : raise_from ( LinkException ( 'Receive thread failure' ) , self . __recv_exc ) elif self . __send_exc : raise_from ( LinkException ( 'Send thread failure' ) , self . __send_exc ) else : raise LinkException ( 'Unknown link failure (timeout reached)' ) else : raise LinkException ( 'amqplink already started' ) | start connection threads blocks until started |
38,164 | def is_alive ( self ) : if self . __send_ready . is_set ( ) and self . __recv_ready . is_set ( ) : if self . __send_thread is not None and self . __recv_thread is not None : return self . __send_thread . is_alive ( ) and self . __recv_thread . is_alive ( ) return False | Helper function to show if send & recv Threads are running |
38,165 | def stop ( self ) : self . __end . set ( ) if self . __recv_thread : self . __recv_thread . join ( ) self . __recv_thread = None if self . __send_thread : self . __send_thread . join ( ) self . __send_thread = None | disconnect blocks until stopped |
38,166 | def __get_ssl_context ( cls , sslca = None ) : if ( ( version_info [ 0 ] == 2 and ( version_info [ 1 ] >= 7 and version_info [ 2 ] >= 5 ) ) or ( version_info [ 0 ] == 3 and version_info [ 1 ] >= 4 ) ) : logger . debug ( 'SSL method for 2.7.5+ / 3.4+' ) from ssl import SSLContext , PROTOCOL_TLSv1_2 , CERT_REQUIRED , OP_NO_COMPRESSION ctx = SSLContext ( PROTOCOL_TLSv1_2 ) ctx . set_ciphers ( 'HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH' ) ctx . options |= OP_NO_COMPRESSION if sslca : ctx . load_verify_locations ( sslca ) ctx . verify_mode = CERT_REQUIRED ctx . check_hostname = False else : from ssl import Purpose ctx . load_default_certs ( purpose = Purpose . SERVER_AUTH ) ctx . verify_mode = CERT_REQUIRED ctx . check_hostname = True elif version_info [ 0 ] == 3 and version_info [ 1 ] < 4 : logger . debug ( 'Using SSL method for 3.2+, < 3.4' ) from ssl import SSLContext , CERT_REQUIRED , PROTOCOL_SSLv23 , OP_NO_SSLv2 , OP_NO_SSLv3 , OP_NO_TLSv1 ctx = SSLContext ( PROTOCOL_SSLv23 ) ctx . options |= ( OP_NO_SSLv2 | OP_NO_SSLv3 | OP_NO_TLSv1 ) ctx . set_ciphers ( 'HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH' ) if sslca : ctx . load_verify_locations ( sslca ) ctx . verify_mode = CERT_REQUIRED else : ctx . set_default_verify_paths ( ) ctx . verify_mode = CERT_REQUIRED else : raise Exception ( "Unsupported Python version %s" % '.' . join ( str ( item ) for item in version_info [ : 3 ] ) ) return ctx | Make an SSLConext for this Python version using public or sslca |
38,167 | def __recv_cb ( self , msg ) : try : self . __msg_callback ( msg ) except : logger . exception ( "AmqpLink.__recv_cb exception calling msg_callback" ) finally : self . __last_id = msg . delivery_tag self . __unacked += 1 | Calls user - provided callback and marks message for Ack regardless of success |
38,168 | def __send_run ( self ) : while not self . __end . is_set ( ) : try : with Connection ( userid = self . __prefix + self . __epid , password = self . __passwd , virtual_host = self . __vhost , heartbeat = self . __heartbeat , connect_timeout = self . __socket_timeout , operation_timeout = self . __socket_timeout , ssl = self . __get_ssl_context ( self . __sslca ) , host = self . __host ) as conn , conn . channel ( auto_encode_decode = False ) as channel : self . __send_channel = channel self . __send_exc_clear ( log_if_exc_set = 'reconnected' ) self . __send_ready . set ( ) try : self . __send_ready_callback ( self . __send_exc_time ) while not self . __end . is_set ( ) : with self . __send_lock : try : conn . drain_events ( 0 ) except ( BlockingIOError , SocketTimeout ) : pass conn . heartbeat_tick ( ) self . __end . wait ( .25 ) finally : with self . __send_lock : self . __send_ready . clear ( ) except exceptions . AccessRefused : self . __send_log_set_exc_and_wait ( 'Access Refused (Credentials already in use?)' ) except exceptions . ConnectionForced : self . __send_log_set_exc_and_wait ( 'Disconnected by broker (ConnectionForced)' ) except SocketTimeout : self . __send_log_set_exc_and_wait ( 'SocketTimeout exception. wrong credentials, vhost or prefix?' ) except SSLError : self . __send_log_set_exc_and_wait ( 'ssl.SSLError Bad Certificate?' ) except ( exceptions . AMQPError , SocketError ) : self . __send_log_set_exc_and_wait ( 'amqp/transport failure, sleeping before retry' ) except : self . __send_log_set_exc_and_wait ( 'unexpected failure, exiting' , wait_seconds = 0 ) break logger . debug ( 'finished' ) | Send request thread |
38,169 | def __send_log_set_exc_and_wait ( self , msg , level = None , wait_seconds = CONN_RETRY_DELAY_SECONDS ) : logger . log ( ( ( logging . DEBUG if self . __send_exc else logging . ERROR ) if level is None else level ) , msg , exc_info = DEBUG_ENABLED ) self . __send_exc_time = monotonic ( ) self . __send_exc = exc_info ( ) [ 1 ] self . __end . wait ( wait_seconds ) | To be called in exception context only . |
38,170 | def __send_exc_clear ( self , log_if_exc_set = None ) : if not ( log_if_exc_set is None or self . __send_exc is None ) : logger . info ( log_if_exc_set ) self . __send_exc_time = None self . __send_exc = None | Clear send exception and time . If exception was previously was set optionally log log_if_exc_set at INFO level . |
38,171 | def expand_idx_mimetype ( type_ ) : if isinstance ( type_ , unicode_type ) : match = __IDX_PATTERN . match ( type_ ) return __IDX_MAPPING . get ( match . group ( 1 ) , type_ ) if match else type_ else : return type_ | Returns long equivalent of type_ if available otherwise type_ itself . Does not raise exceptions |
38,172 | def restore_event ( self , requestId ) : with self . __requests : if requestId not in self . __requests : self . __requests [ requestId ] = RequestEvent ( requestId ) return True return False | restore an event based on the requestId . |
38,173 | def simulate_feeddata ( self , feedid , data , mime = None , time = None ) : feedid = Validation . guid_check_convert ( feedid ) mime = Validation . mime_check_convert ( mime , allow_none = True ) Validation . datetime_check_convert ( time , allow_none = True , to_iso8601 = False ) self . __simulate_feeddata ( feedid , data , mime , datetime . utcnow ( ) if time is None else time ) | Send feed data |
38,174 | def stop ( self ) : if self . __end . is_set ( ) : return self . __end . set ( ) self . __send_retry_requests_timer . cancel ( ) self . __threadpool . stop ( ) self . __crud_threadpool . stop ( ) self . __amqplink . stop ( ) self . __network_retry_thread . join ( ) with self . __requests : shutdown = LinkShutdownException ( 'Client stopped' ) for req in self . __requests . values ( ) : req . exception = shutdown req . _set ( ) self . __clear_references ( req , remove_request = False ) if self . __requests : logger . warning ( '%d unfinished request(s) discarded' , len ( self . __requests ) ) self . __requests . clear ( ) self . __network_retry_thread = None self . __network_retry_queue = None self . __container_params = None | Stop the Client disconnect from queue |
38,175 | def _request ( self , resource , rtype , action = None , payload = None , offset = None , limit = None , requestId = None , is_crud = False ) : end = self . __end if end . is_set ( ) : raise LinkShutdownException ( 'Client stopped' ) rng = None if offset is not None and limit is not None : Validation . limit_offset_check ( limit , offset ) rng = "%d/%d" % ( offset , limit ) with self . __requests : if requestId is None : requestId = self . __new_request_id ( ) elif requestId in self . __requests : raise ValueError ( 'requestId %s already in use' % requestId ) inner_msg = self . __make_innermsg ( resource , rtype , requestId , action , payload , rng ) self . __requests [ requestId ] = ret = RequestEvent ( requestId , inner_msg , is_crud = is_crud ) if not self . __retry_enqueue ( PreparedMessage ( inner_msg , requestId ) ) : raise LinkShutdownException ( 'Client stopping' ) return ret | _request amqp queue publish helper |
38,176 | def __bytes_to_share_data ( self , payload ) : rbytes = payload [ P_DATA ] mime = payload [ P_MIME ] if mime is None or not self . __auto_encode_decode : return rbytes , mime mime = expand_idx_mimetype ( mime ) . lower ( ) try : if mime == 'application/ubjson' : return ubjloadb ( rbytes ) , None elif mime == 'text/plain; charset=utf8' : return rbytes . decode ( 'utf-8' ) , None else : return rbytes , mime except : logger . warning ( 'auto-decode failed, returning bytes' , exc_info = DEBUG_ENABLED ) return rbytes , mime | Attempt to auto - decode data |
38,177 | def __make_hash ( cls , innermsg , token , seqnum ) : hobj = hmacNew ( token , digestmod = hashfunc ) hobj . update ( innermsg ) hobj . update ( cls . __byte_packer ( seqnum ) ) return hobj . digest ( ) | return the hash for this innermsg token seqnum return digest bytes |
38,178 | def __request_mark_sent ( self , requestId ) : with self . __requests : try : req = self . __requests [ requestId ] except KeyError : pass else : req . exception = None req . _send_time = monotonic ( ) | Set send time & clear exception from request if set ignoring non - existent requests |
38,179 | def __fire_callback ( self , type_ , * args , ** kwargs ) : called = False plain_submit = self . __threadpool . submit with self . __callbacks : submit = self . __crud_threadpool . submit if type_ in _CB_CRUD_TYPES else plain_submit for func , serialised_if_crud in self . __callbacks [ type_ ] : called = True ( submit if serialised_if_crud else plain_submit ) ( func , * args , ** kwargs ) return called | Returns True if at least one callback was called |
38,180 | def __handle_known_solicited ( self , msg ) : with self . __requests : try : req = self . __requests [ msg [ M_CLIENTREF ] ] except KeyError : return False if self . __handle_low_seq_resend ( msg , req ) : return True perform_cb = finish = False if msg [ M_TYPE ] not in _RSP_NO_REF : self . __update_existing ( msg , req ) if msg [ M_TYPE ] in _RSP_TYPE_FINISH : finish = True perform_cb = ( msg [ M_TYPE ] == E_DUPLICATED ) elif msg [ M_TYPE ] not in _RSP_TYPE_ONGOING : perform_cb = True else : logger . warning ( 'Reference unexpected for request %s of type %s' , msg [ M_CLIENTREF ] , msg [ M_TYPE ] ) if perform_cb : self . __perform_unsolicited_callbacks ( msg ) if finish : req . success = msg [ M_TYPE ] in _RSP_TYPE_SUCCESS req . payload = msg [ M_PAYLOAD ] self . __clear_references ( req ) if req . is_crud : self . __crud_threadpool . submit ( req . _set ) else : req . _set ( ) return True | returns True if message has been handled as a solicited response |
38,181 | def __clear_references ( self , request , remove_request = True ) : if remove_request : with self . __requests : self . __requests . pop ( request . id_ ) if not request . success : with self . __pending_subs : self . __pending_subs . pop ( request . id_ , None ) with self . __pending_controls : self . __pending_controls . pop ( request . id_ , None ) | Remove any internal references to the given request |
38,182 | def __perform_unsolicited_callbacks ( self , msg ) : type_ = msg [ M_TYPE ] payload = msg [ M_PAYLOAD ] if type_ in _RSP_PAYLOAD_CB_MAPPING : self . __fire_callback ( _RSP_PAYLOAD_CB_MAPPING [ type_ ] , msg ) elif type_ == E_FEEDDATA : self . __simulate_feeddata ( payload [ P_FEED_ID ] , * self . __decode_data_time ( payload ) ) elif type_ == E_SUBSCRIBED : self . __fire_callback ( _CB_SUBSCRIPTION , payload ) else : logger . error ( 'Unexpected message type for unsolicited callback %s' , type_ ) | Callbacks for which a client reference is either optional or does not apply at all |
38,183 | def roles ( self , roles_list ) : if roles_list and isinstance ( roles_list , list ) : self . roles = [ ] . extend ( roles_list ) elif roles_list and isinstance ( roles_list , basestring ) : self . roles = [ role . lower ( ) for role in roles_list . split ( ',' ) ] | Set the roles for the current launch . |
38,184 | def process_params ( self , params ) : for key , val in params . items ( ) : if key in LAUNCH_DATA_PARAMETERS and val != 'None' : if key == 'roles' : if isinstance ( val , list ) : self . roles = list ( val ) else : self . roles = val . split ( ',' ) else : setattr ( self , key , touni ( val ) ) elif 'custom_' in key : self . custom_params [ key ] = touni ( val ) elif 'ext_' in key : self . ext_params [ key ] = touni ( val ) | Populates the launch data from a dictionary . Only cares about keys in the LAUNCH_DATA_PARAMETERS list or that start with custom_ or ext_ . |
38,185 | def run ( self , background = False ) : if self . __bgthread : raise Exception ( 'run has already been called (since last stop)' ) self . __shutdown . clear ( ) if background : self . __bgthread = Thread ( target = self . __run , name = ( 'bg_' + self . __client . agent_id ) ) self . __bgthread . daemon = True self . __bgthread . start ( ) else : self . __run ( ) | Runs on_startup main and on_shutdown blocking until finished unless background is set . |
38,186 | def _batch_report ( cls , request ) : if not newrelic : return metrics_cache = cls . _get_metrics_cache ( ) try : newrelic . agent . add_custom_parameter ( 'user_id' , request . user . id ) except AttributeError : pass for key , value in metrics_cache . data . items ( ) : newrelic . agent . add_custom_parameter ( key , value ) | Report the collected custom metrics to New Relic . |
38,187 | def process_request ( self , request ) : if self . _is_enabled ( ) : self . _cache . set ( self . guid_key , six . text_type ( uuid4 ( ) ) ) log_prefix = self . _log_prefix ( u"Before" , request ) self . _cache . set ( self . memory_data_key , self . _memory_data ( log_prefix ) ) | Store memory data to log later . |
38,188 | def process_response ( self , request , response ) : if self . _is_enabled ( ) : log_prefix = self . _log_prefix ( u"After" , request ) new_memory_data = self . _memory_data ( log_prefix ) log_prefix = self . _log_prefix ( u"Diff" , request ) cached_memory_data_response = self . _cache . get_cached_response ( self . memory_data_key ) old_memory_data = cached_memory_data_response . get_value_or_default ( None ) self . _log_diff_memory_data ( log_prefix , new_memory_data , old_memory_data ) return response | Logs memory data after processing response . |
38,189 | def _log_prefix ( self , prefix , request ) : cached_guid_response = self . _cache . get_cached_response ( self . guid_key ) cached_guid = cached_guid_response . get_value_or_default ( u"without_guid" ) return u"{} request '{} {} {}'" . format ( prefix , request . method , request . path , cached_guid ) | Returns a formatted prefix for logging for the given request . |
38,190 | def _memory_data ( self , log_prefix ) : machine_data = psutil . virtual_memory ( ) process = psutil . Process ( ) process_data = { 'memory_info' : process . get_memory_info ( ) , 'ext_memory_info' : process . get_ext_memory_info ( ) , 'memory_percent' : process . get_memory_percent ( ) , 'cpu_percent' : process . get_cpu_percent ( ) , } log . info ( u"%s Machine memory usage: %s; Process memory usage: %s" , log_prefix , machine_data , process_data ) return { 'machine_data' : machine_data , 'process_data' : process_data , } | Returns a dict with information for current memory utilization . Uses log_prefix in log statements . |
38,191 | def _log_diff_memory_data ( self , prefix , new_memory_data , old_memory_data ) : def _vmem_used ( memory_data ) : return memory_data [ 'machine_data' ] . used def _process_mem_percent ( memory_data ) : return memory_data [ 'process_data' ] [ 'memory_percent' ] def _process_rss ( memory_data ) : return memory_data [ 'process_data' ] [ 'memory_info' ] . rss def _process_vms ( memory_data ) : return memory_data [ 'process_data' ] [ 'memory_info' ] . vms if new_memory_data and old_memory_data : log . info ( u"%s Diff Vmem used: %s, Diff percent memory: %s, Diff rss: %s, Diff vms: %s" , prefix , _vmem_used ( new_memory_data ) - _vmem_used ( old_memory_data ) , _process_mem_percent ( new_memory_data ) - _process_mem_percent ( old_memory_data ) , _process_rss ( new_memory_data ) - _process_rss ( old_memory_data ) , _process_vms ( new_memory_data ) - _process_vms ( old_memory_data ) , ) | Computes and logs the difference in memory utilization between the given old and new memory data . |
38,192 | def set_all_tiers ( key , value , django_cache_timeout = DEFAULT_TIMEOUT ) : DEFAULT_REQUEST_CACHE . set ( key , value ) django_cache . set ( key , value , django_cache_timeout ) | Caches the value for the provided key in both the request cache and the django cache . |
38,193 | def _get_cached_response_from_django_cache ( key ) : if TieredCache . _should_force_django_cache_miss ( ) : return CachedResponse ( is_found = False , key = key , value = None ) cached_value = django_cache . get ( key , _CACHE_MISS ) is_found = cached_value is not _CACHE_MISS return CachedResponse ( is_found , key , cached_value ) | Retrieves a CachedResponse for the given key from the django cache . |
38,194 | def _set_request_cache_if_django_cache_hit ( key , django_cached_response ) : if django_cached_response . is_found : DEFAULT_REQUEST_CACHE . set ( key , django_cached_response . value ) | Sets the value in the request cache if the django cached response was a hit . |
38,195 | def _get_and_set_force_cache_miss ( request ) : if not ( request . user and request . user . is_active and request . user . is_staff ) : force_cache_miss = False else : force_cache_miss = request . GET . get ( FORCE_CACHE_MISS_PARAM , 'false' ) . lower ( ) == 'true' DEFAULT_REQUEST_CACHE . set ( SHOULD_FORCE_CACHE_MISS_KEY , force_cache_miss ) | Gets value for request query parameter FORCE_CACHE_MISS and sets it in the default request cache . |
38,196 | def _should_force_django_cache_miss ( cls ) : cached_response = DEFAULT_REQUEST_CACHE . get_cached_response ( SHOULD_FORCE_CACHE_MISS_KEY ) return False if not cached_response . is_found else cached_response . value | Returns True if the tiered cache should force a cache miss for the django cache and False otherwise . |
38,197 | def check_convert_string ( obj , name = None , no_leading_trailing_whitespace = True , no_whitespace = False , no_newline = True , whole_word = False , min_len = 1 , max_len = 0 ) : if not name : name = 'Argument' obj = ensure_unicode ( obj , name = name ) if no_whitespace : if _PATTERN_WHITESPACE . match ( obj ) : raise ValueError ( '%s cannot contain whitespace' % name ) elif no_leading_trailing_whitespace and _PATTERN_LEAD_TRAIL_WHITESPACE . match ( obj ) : raise ValueError ( '%s contains leading/trailing whitespace' % name ) if ( min_len and len ( obj ) < min_len ) or ( max_len and len ( obj ) > max_len ) : raise ValueError ( '%s too short/long (%d/%d)' % ( name , min_len , max_len ) ) if whole_word : if not _PATTERN_WORD . match ( obj ) : raise ValueError ( '%s can only contain alphanumeric (unicode) characters, numbers and the underscore' % name ) elif no_newline and '\n' in obj : raise ValueError ( '%s cannot contain line breaks' % name ) return obj | Ensures the provided object can be interpreted as a unicode string optionally with additional restrictions imposed . By default this means a non - zero length string which does not begin or end in whitespace . |
38,198 | def __valid_url ( cls , url ) : bits = urlparse ( url ) return ( ( bits . scheme == "http" or bits . scheme == "https" ) and _PATTERN_URL_PART . match ( bits . netloc ) and _PATTERN_URL_PART . match ( bits . path ) ) | Expects input to already be a valid string |
38,199 | def location_check ( lat , lon ) : if not ( isinstance ( lat , number_types ) and - 90 <= lat <= 90 ) : raise ValueError ( "Latitude: '{latitude}' invalid" . format ( latitude = lat ) ) if not ( isinstance ( lon , number_types ) and - 180 <= lon <= 180 ) : raise ValueError ( "Longitude: '{longitude}' invalid" . format ( longitude = lon ) ) | For use by Core client wrappers |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.