idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
10,000
def unshift ( view_or_constant , style = nil , opts = { } , & block ) opts [ :at_index ] = 0 opts [ :style ] = style opts [ :block ] = block if block add_subview view_or_constant , opts end
Just like append but inserts the view at index 0 of the subview array
10,001
def build ( view , style = nil , opts = { } , & block ) opts [ :do_not_add ] = true opts [ :style ] = style opts [ :block ] = block if block add_subview view , opts end
Build a view similar to create and append but only inits an existing view . Usefull in collectionview cells for example
10,002
def universal_validation_checks ( data , options = { } ) return true if RubyMotionQuery :: RMQ . debugging? return true if ( options [ :allow_blank ] && ( data . nil? || data . empty? ) ) return true if ( options [ :white_list ] && options [ :white_list ] . include? ( data ) ) false end
this method shortcuts specific validation rules . As such it should only be added to for universal validation needs . It must be kept as efficient as possible .
10,003
def log_detailed ( label , params = { } ) return unless RMQ . app . development? || RMQ . app . test? objects = params [ :objects ] skip_first_caller = params [ :skip_first_caller ] if block_given? && ! objects objects = yield end callers = caller callers = callers . drop ( 1 ) if skip_first_caller out = %( ----...
Warning this is very slow
10,004
def assert ( truthy , label = nil , objects = nil ) if ( RMQ . app . development? || RMQ . app . test? ) && ! truthy label ||= 'Assert failed' if block_given? && ! objects objects = yield end log_detailed label , objects : objects , skip_first_caller : true end end
Warning this is very slow to output log checking truthy however is basically as performant as an if statement
10,005
def subviews_bottom_right ( view , args = { } ) w = 0 h = 0 view . subviews . each do | subview | rect = subview . rmq . frame w = [ rect . right , w ] . max h = [ rect . bottom , h ] . max end rect = view . rmq . frame w = rect . width if ( w == 0 || args [ :only_height ] ) h = rect . height if ( h == 0 || args [ :onl...
Calculates the bottom right of a view using its subviews
10,006
def context = ( value ) if value if value . is_a? ( UIViewController ) @context = RubyMotionQuery :: RMQ . weak_ref ( value ) elsif value . is_a? ( UIView ) @context = value end else @context = nil end @context end
This is mostly used internally
10,007
def selected if @selected_dirty @_selected = [ ] if RMQ . is_blank? ( self . selectors ) @_selected << context_or_context_view else working_selectors = self . selectors . dup extract_views_from_selectors ( @_selected , working_selectors ) unless RMQ . is_blank? ( working_selectors ) subviews = all_subviews_for ( root_v...
The UIViews currently selected
10,008
def wrap ( * views ) views . flatten! views . select! { | v | v . is_a? ( UIView ) } RMQ . create_with_array_and_selectors ( views , views , views . first , self ) end
Wraps 1 or more views in an rmq instance .
10,009
def log ( opt = nil ) if opt == :tree puts tree_to_s ( selected ) return end wide = ( opt == :wide ) out = "\n object_id | class | style_name | frame |" out << "\n" unless wide out << " sv id | superview | subviews count | tags ...
Super useful in the console . log outputs to the console a table of the selected views
10,010
def apply_to_method ( method ) filtered_advices = filter_advices advices , method return if filtered_advices . empty? logger . debug 'apply-to-method' , method scope ||= context . instance_method_type ( method ) recreate_method method , filtered_advices , scope end
Applies advices to a given method
10,011
def define_methods_for_advice_blocks advices . each do | advice | next if advice . raw? next unless advice . advice_block context . send :define_method , advice . with_method , advice . advice_block context . send :private , advice . with_method end end
Defines on a target element new methods that will contain advices logic as long as their blocks . Then we can invoke advices logic as a normal methods In a way it just casts a block to methods for peformance reasons If we have advices that just execute already existing methods this won t create anything
10,012
def apply_to_methods methods = [ @options [ :method ] || @options [ :methods ] ] methods . compact! methods . flatten! if ! methods . empty? && methods . all? { | method | method . is_a? ( String ) || method . is_a? ( Symbol ) } methods . each do | method | apply_to_method ( method . to_s ) end return end context . pub...
Will apply all the advices to all methods that match
10,013
def invoke_deferred_logics logics = @aspect . class . storage . deferred_logics return if logics . empty? logics . each do | logic | result = logic . apply context , aspect if advices . detect { | advice | advice . use_deferred_logic? logic } @deferred_logic_results ||= { } @deferred_logic_results [ logic ] = result en...
Invokes deferred logics blocks on a target element and stores deferred logic invokations results
10,014
def add_method_hooks eigen_class = @target . singleton_class if @options [ :class_methods ] return unless @target . is_a? ( Module ) orig_singleton_method_added = @target . method ( :singleton_method_added ) eigen_class . send :define_method , :singleton_method_added do | method | aspector_singleton_method_added ( meth...
Redefines singleton_method_added and method_added methods so they are monitored If new method is added we will apply to it appropriate advices
10,015
def recreate_method ( method , advices , scope ) context . instance_variable_set ( :@aspector_creating_method , true ) raw_advices = advices . select ( & :raw? ) if raw_advices . size > 0 raw_advices . each do | advice | if @target . is_a? ( Module ) && ! @options [ :class_methods ] @target . class_exec method , self ,...
Recreates a given method applying all the advices one by one
10,016
def message ( * args ) msg = [ ] if context . is_a? Aspector :: Base msg << context . class . to_s msg << context . target . to_s else msg << context . to_s end msg += args msg . join ( ' | ' ) end
Creates a full messages that we want to log
10,017
def legend ( labels , height : , right : 0 , colors : [ ] ) left = @pdf . bounds . width / 2 box ( x : left , y : @pdf . bounds . top , w : left , h : height ) do x = @pdf . bounds . right - right options = { size : 7 , height : @pdf . bounds . height , valign : :center } labels . each . with_index do | label , i | ind...
Draws the graph legend with the given labels .
10,018
def horizontal_line ( y , options = { } ) with options do at = y + @bottom @pdf . stroke_horizontal_line left , @pdf . bounds . right - right , at : at end end
Draws a horizontal line .
10,019
def legend_item ( label , x , color , options ) size , symbol_padding , entry_padding = 5 , 3 , 12 x -= @pdf . width_of ( label , size : 7 ) . ceil @pdf . text_box label , options . merge ( at : [ x , @pdf . bounds . height ] ) x -= ( symbol_padding + size ) with fill_color : color do @pdf . fill_rectangle [ x , @pdf ....
Draws a single item of the legend which includes the label and the symbol with the matching color . Labels are written from right to left .
10,020
def with ( new_values = { } ) transparency = new_values . delete ( :transparency ) { 1.0 } old_values = Hash [ new_values . map { | k , _ | [ k , @pdf . public_send ( k ) ] } ] new_values . each { | k , new_value | @pdf . public_send "#{k}=" , new_value } @pdf . transparent ( transparency ) do @pdf . stroke { yield } e...
Convenience method to wrap a block by setting and unsetting a Prawn property such as line_width .
10,021
def primary_group_for ( user ) Etc . endpwent Etc . endgrent user = if user . is_a? ( Integer ) Etc . getpwuid ( user ) else Etc . getpwnam ( user . to_s ) end Etc . getgrgid ( user . gid ) . name rescue ArgumentError user . to_s end
Try to find the primary group name for a given user .
10,022
def write ( chunk ) body = '' chunk . msgpack_each { | ( tag , time , record ) | begin index = expand_param ( @index , tag , time , record ) sourcetype = expand_param ( @sourcetype , tag , time , record ) event_host = expand_param ( @event_host , tag , time , record ) token = expand_param ( @token , tag , time , record...
Loop through all records and sent them to Splunk
10,023
def find_cookbook_name ( run_context , filename ) possibles = { } Poise . debug ( "[Poise] Checking cookbook for #{filename.inspect}" ) run_context . cookbook_collection . each do | name , ver | if ver . respond_to? ( :halite_root ) if filename . start_with? ( File . join ( ver . halite_root , '' ) ) Poise . debug ( "[...
Find the cookbook name for a given filename . The can used to find the cookbook that corresponds to a caller of a file .
10,024
def ancestor_send ( obj , msg , * args , default : nil , ignore : [ default ] ) obj = obj . class unless obj . is_a? ( Module ) ancestors = [ ] if obj . respond_to? ( :superclass ) ancestors << obj . superclass end ancestors . concat ( obj . ancestors . drop ( 1 ) ) ancestors . each do | mod | if mod . respond_to? ( ms...
Try to find an ancestor to call a method on .
10,025
def parameterized_module ( mod , & block ) raise Poise :: Error . new ( "Cannot parameterize an anonymous module" ) unless mod . name && ! mod . name . empty? parent_name_parts = mod . name . split ( / / ) mod_name = parent_name_parts . pop parent = parent_name_parts . inject ( Object ) { | memo , name | memo . const_g...
Create a helper to invoke a module with some parameters .
10,026
def check_block_arity! ( block , args ) obj = Object . new obj . define_singleton_method ( :block , & block ) block = obj . method ( :block ) . to_proc required_args = block . arity < 0 ? ~ block . arity : block . arity if args . length < required_args || ( block . arity >= 0 && args . length > block . arity ) raise Ar...
Check that the given arguments match the given block . This is needed because Ruby will nil - pad mismatched argspecs on blocks rather than error .
10,027
def oauth_apps apps = [ ] response = client . get ( "#{@api_end_point}#{self.id}/oauth2" ) rescue nil if response response [ 'data' ] . each do | attributes | apps << Kong :: OAuthApp . new ( attributes ) end end apps end
List OAuth applications
10,028
def dampening_half_time return nil if dampening . nil? || dampening_routemap_configured? if dampening . is_a? ( Array ) && ! dampening . empty? dampening [ 0 ] . to_i else default_dampening_half_time end end
For all of the following dampening getters half_time reuse_time suppress_time and max_suppress_time return nil if dampening is not configured but also return nil if a dampening routemap is configured because they are mutually exclusive .
10,029
def method_missing ( * args ) name = args [ 0 ] . to_s if args . length == 1 if name =~ / / config_get_default ( 'bgp_af' , Regexp . last_match ( 1 ) ) else config_get ( 'bgp_af' , name , @get_args ) end elsif args . length == 2 && name =~ / / set_args_keys ( state : args [ 1 ] ? '' : 'no' ) config_set ( 'bgp_af' , Reg...
Universal Getter Default Getter and Setter
10,030
def respond_to? ( method_sym , _include_private = false ) name = method_sym . to_s key = :getter? if name =~ / / name = Regexp . last_match ( 1 ) return false if name == 'table_map' || name == 'table_map_filter' key = :setter? elsif name =~ / / name = Regexp . last_match ( 1 ) key = :default_value? end begin ref = node...
Is the given name available in the YAML?
10,031
def ace_get str = config_get ( 'acl' , 'ace' , @get_args ) return nil if str . nil? remark = Regexp . new ( '(?<seqno>\d+) remark (?<remark>.*)' ) . match ( str ) return remark unless remark . nil? return icmp_ace_get ( str ) if str . include? ( 'icmp' ) regexp = Regexp . new ( '(?<seqno>\d+) (?<action>\S+)' ' *(?<prot...
common ace getter
10,032
def icmp_ace_get ( str ) str . sub! ( 'fragments ' , '' ) regexp = Regexp . new ( '(?<seqno>\d+) (?<action>\S+)' ' *(?<proto>\d+|\S+)' ' *(?<src_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)' ' *(?<dst_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgro...
icmp ace getter
10,033
def hsrp_delay_minimum = ( val ) Feature . hsrp_enable if val config_set ( 'interface' , 'hsrp_delay' , name : @name , minimum : 'minimum' , min : val , reload : '' , rel : '' ) end
hsrp delay minimum and reload are in the same CLI but both can be set independent of each other
10,034
def bd_total_range_with_vlans hash = Vlan . vlans arr = [ ] hash . keys . each do | id | arr << id . to_i end Utils . array_to_str ( arr ) ret_arr = [ ] ret_arr << Utils . array_to_str ( arr ) end
bridge - domain and vlans are mutually exclusive so when there are vlans we need to remove them from the bd range while restting
10,035
def hs_weight ( hs , wt ) if hs != hot_standby && hot_standby == default_hot_standby self . lweight = wt unless weight == wt self . lhot_standby = hs elsif hs != hot_standby && hot_standby != default_hot_standby self . lhot_standby = hs self . lweight = wt unless weight == wt elsif wt != weight && weight == default_wei...
Call this for setting hot_standby and weight together because the CLI is pretty weird and it accepts these params in a very particular way and they cannot even be reset unless proper order is followed
10,036
def curr_bd_vni_hash final_bd_vni = { } curr_vni = config_get ( 'bridge_domain_vni' , 'member_vni' ) curr_bd_vni = config_get ( 'bridge_domain_vni' , 'member_vni_bd' ) return final_bd_vni if curr_vni . empty? || curr_bd_vni . empty? curr_vni_list = BridgeDomainVNI . string_to_array ( curr_vni ) curr_bd_vni_list = Bridg...
Example clis ; system bridge - domain 101 - 200 bridge - domain 101 - 200 bridge - domain 101 - 110 120 141 - 145 180 member vni 6001 - 6011 5041 - 5044 8000 9000
10,037
def massage_structured ( get_args , ref ) return [ get_args , ref ] unless ref . hash [ 'get_data_format' ] == :nxapi_structured if ref . hash [ 'get_value' ] . is_a? ( Array ) && ref . hash [ 'get_value' ] . size >= 2 ref . hash [ 'get_value' ] = get_args [ :value ] ref . hash [ 'drill_down' ] = true get_args [ :value...
The yaml file may specifiy an Array as the get_value to drill down into nxapi_structured table output . The table may contain multiple rows but only one of the rows has the interesting data .
10,038
def massage ( value , ref ) Cisco :: Logger . debug "Massaging '#{value}' (#{value.inspect})" value = drill_down_structured ( value , ref ) if value . is_a? ( Array ) && ! ref . multiple fail "Expected zero/one value but got '#{value}'" if value . length > 1 value = value [ 0 ] end if ( value . nil? || value . to_s . e...
Attempt to massage the given value into the format specified by the given CmdRef object .
10,039
def lookup ( feature , name ) value = @hash [ feature ] value = value [ name ] if value . is_a? Hash fail IndexError , "No CmdRef defined for #{feature}, #{name}" if value . nil? value end
Get the command reference
10,040
def validate_yaml ( node , filename , depth = 0 , parents = nil ) return unless node && ( mapping? ( node ) || node . children ) unless node . class . ancestors . any? { | name | / / =~ name . to_s } depth += 1 end debug "Validating #{node.class} at depth #{depth}" unless mapping? ( node ) node . children . each do | c...
Validate the YAML node tree before converting it into Ruby data structures .
10,041
def load_yaml ( yaml_file ) fail "File #{yaml_file} doesn't exist." unless File . exist? ( yaml_file ) rescue_errors = [ :: StandardError , :: Psych :: SyntaxError ] yaml_parsed = File . open ( yaml_file , 'r' ) do | f | begin YAML . parse ( f ) rescue * rescue_errors => e raise "unable to parse #{yaml_file}: #{e}" end...
Read in yaml file . The expectation is that a file corresponds to a feature
10,042
def message_digest_key_set ( keyid , algtype , enctype , enc ) current_keyid = message_digest_key_id if keyid == default_message_digest_key_id && current_keyid != keyid config_set ( 'interface_ospf' , 'message_digest_key_set' , @interface . name , 'no' , current_keyid , '' , '' , '' ) elsif keyid != default_message_dig...
interface %s %s ip ospf message - digest - key %d %s %d %s
10,043
def bfd val = config_get ( 'interface_ospf' , 'bfd' , @interface . name ) return if val . nil? val . include? ( 'disable' ) ? false : true end
CLI can be either of the following or none ip ospf bfd ip ospf bfd disable
10,044
def bfd = ( val ) return if val == bfd Feature . bfd_enable state = ( val == default_bfd ) ? 'no' : '' disable = val ? '' : 'disable' config_set ( 'interface_ospf' , 'bfd' , @interface . name , state , disable ) end
interface %s %s ip ospf bfd %s
10,045
def network_type = ( type ) no_cmd = ( type == default_network_type ) ? 'no' : '' network = ( type == default_network_type ) ? '' : type network = 'point-to-point' if type . to_s == 'p2p' config_set ( 'interface_ospf' , 'network_type' , @interface . name , no_cmd , network ) end
interface %s %s ip ospf network %s
10,046
def passive_interface = ( enable ) fail TypeError unless enable == true || enable == false config_set ( 'interface_ospf' , 'passive_interface' , @interface . name , enable ? '' : 'no' ) end
interface %s %s ip ospf passive - interface
10,047
def priority = ( val ) no_cmd = ( val == default_priority ) ? 'no' : '' pri = ( val == default_priority ) ? '' : val config_set ( 'interface_ospf' , 'priority' , @interface . name , no_cmd , pri ) end
interface %s ip ospf priority %d
10,048
def transmit_delay = ( val ) no_cmd = ( val == default_transmit_delay ) ? 'no' : '' delay = ( val == default_transmit_delay ) ? '' : val config_set ( 'interface_ospf' , 'transmit_delay' , @interface . name , no_cmd , delay ) end
interface %s ip ospf transmit - delay %d
10,049
def destroy return unless Feature . bfd_enabled? [ :interval , :ipv4_interval , :ipv6_interval , :fabricpath_interval , :echo_interface , :echo_rx_interval , :ipv4_echo_rx_interval , :ipv6_echo_rx_interval , :fabricpath_vlan , :slow_timer , :ipv4_slow_timer , :ipv6_slow_timer , :fabricpath_slow_timer , :startup_timer ,...
Reset everything back to default
10,050
def domain = ( d ) d = d . to_s fail ArgumentError unless d . length . between? ( 1 , MAX_VTP_DOMAIN_NAME_SIZE ) config_set ( 'vtp' , 'domain' , domain : d ) end
Set vtp domain name
10,051
def password password = config_get ( 'vtp' , 'password' ) if Feature . vtp_enabled? return '' if password . nil? || password == '\\' password rescue Cisco :: RequestNotSupported => e return '' if e . message [ / / ] end
Get vtp password
10,052
def password = ( password ) fail TypeError if password . nil? fail TypeError unless password . is_a? String fail ArgumentError if password . length > MAX_VTP_PASSWORD_SIZE Feature . vtp_enable state = ( password == default_password ) ? 'no' : '' config_set ( 'vtp' , 'password' , state : state , password : password ) en...
Set vtp password
10,053
def filename = ( uri ) fail TypeError if uri . nil? Feature . vtp_enable uri = uri . to_s state = uri . empty? ? 'no' : '' config_set ( 'vtp' , 'filename' , state : state , uri : uri ) end
Set vtp filename
10,054
def graceful_restart = ( enable ) if platform == :ios_xr && @vrf != 'default' fail Cisco :: UnsupportedError . new ( 'bgp' , 'graceful_restart' , 'set' , 'graceful_restart is not ' 'configurable ' 'on a per-VRF basis on IOS XR' ) end @set_args [ :state ] = ( enable ? '' : 'no' ) config_set ( 'bgp' , 'graceful_restart' ...
Graceful Restart Setters
10,055
def timer_bgp_keepalive_hold_set ( keepalive , hold ) if keepalive == default_timer_bgp_keepalive && hold == default_timer_bgp_holdtime @set_args [ :state ] = 'no' @set_args [ :keepalive ] = keepalive @set_args [ :hold ] = hold else @set_args [ :state ] = '' @set_args [ :keepalive ] = keepalive @set_args [ :hold ] = ho...
BGP Timers Setters
10,056
def match_community str = config_get ( 'route_map' , 'match_community' , @get_args ) if str . empty? val = default_match_community else val = str . split val . delete ( 'exact-match' ) end val end
match community public private exact - match
10,057
def match_metric str = config_get ( 'route_map' , 'match_metric' , @get_args ) return default_match_metric if str . empty? rarr = [ ] larr = [ ] metrics = str . split deviation = false metrics . each do | metric | deviation = true if metric == '+-' if ! larr . empty? && ! deviation larr << '0' rarr << larr larr = [ ] e...
match metric 1 8 224 + - 9 23 5 + - 8 6
10,058
def match_ospf_area str = config_get ( 'route_map' , 'match_ospf_area' , @get_args ) return if str . nil? str . empty? ? default_match_ospf_area : str . split end
match ospf - area 10 7
10,059
def match_mac_list str = config_get ( 'route_map' , 'match_mac_list' , @get_args ) return if str . nil? str . empty? ? default_match_mac_list : str . split end
match mac - list m1 m2
10,060
def match_evpn_route_type_get arr = config_get ( 'route_map' , 'match_evpn_route_type' , @get_args ) return nil if arr . nil? hash = { } hash [ :type1 ] = false hash [ :type3 ] = false hash [ :type4 ] = false hash [ :type5 ] = false hash [ :type6 ] = false hash [ :type_all ] = false hash [ :type2_all ] = false hash [ :...
match evpn route - type 1 match evpn route - type 2 all match evpn route - type 2 mac - ip match evpn route - type 2 mac - only match evpn route - type 3 etc .
10,061
def set_metric_get hash = { } hash [ :additive ] = false hash [ :bandwidth ] = false hash [ :delay ] = false hash [ :reliability ] = false hash [ :effective_bandwidth ] = false hash [ :mtu ] = false str = config_get ( 'route_map' , 'set_metric' , @get_args ) return hash if str . nil? arr = str . split hash [ :additive ...
set metric 44 55 66 77 88 set metric + 33
10,062
def set_dampening_get hash = { } hash [ :half_life ] = false hash [ :reuse ] = false hash [ :suppress ] = false hash [ :max ] = false str = config_get ( 'route_map' , 'set_dampening' , @get_args ) return hash if str . nil? arr = str . split hash [ :half_life ] = arr [ 0 ] . to_i hash [ :reuse ] = arr [ 1 ] . to_i hash ...
set dampening 6 22 44 55
10,063
def set_as_path_prepend arr = [ ] match = config_get ( 'route_map' , 'set_as_path_prepend' , @get_args ) if arr match . each do | line | next if line . include? ( 'last-as' ) arr = line . strip . split end end arr end
set as - path prepend 55 . 77 44 33 . 5 set as - path prepend last - as 1
10,064
def set_ipv4_default_next_hop str = config_get ( 'route_map' , 'set_ipv4_default_next_hop' , @get_args ) return if str . nil? if str . empty? val = default_set_ipv4_default_next_hop else val = str . split val . delete ( 'load-share' ) end val end
set ip default next - hop 1 . 1 . 1 . 1 2 . 2 . 2 . 2 3 . 3 . 3 . 3
10,065
def set_ipv4_next_hop arr = config_get ( 'route_map' , 'set_ipv4_next_hop' , @get_args ) val = default_set_ipv4_next_hop arr . each do | str | next if str . empty? next if str . include? ( 'peer-address' ) next if str . include? ( 'unchanged' ) next if str . include? ( 'redist-unchanged' ) val = str . split val . delet...
set ip next - hop 1 . 1 . 1 . 1 2 . 2 . 2 . 2 3 . 3 . 3 . 3
10,066
def set_ipv4_next_hop_load_share arr = config_get ( 'route_map' , 'set_ipv4_next_hop' , @get_args ) val = default_set_ipv4_next_hop_load_share arr . each do | str | next if str . empty? return true if str . include? ( 'load-share' ) end val end
set ip next - hop 1 . 1 . 1 . 1 2 . 2 . 2 . 2 3 . 3 . 3 . 3 load - share set ip next - hop load - share
10,067
def set_ipv6_default_next_hop str = config_get ( 'route_map' , 'set_ipv6_default_next_hop' , @get_args ) return if str . nil? if str . empty? val = default_set_ipv6_default_next_hop else val = str . split val . delete ( 'load-share' ) end val end
set ipv6 default next - hop 1 . 1 . 1 . 1 2 . 2 . 2 . 2 3 . 3 . 3 . 3
10,068
def set_ipv6_next_hop arr = config_get ( 'route_map' , 'set_ipv6_next_hop' , @get_args ) val = default_set_ipv6_next_hop arr . each do | str | next if str . empty? next if str . include? ( 'peer-address' ) next if str . include? ( 'unchanged' ) next if str . include? ( 'redist-unchanged' ) val = str . split val . delet...
set ipv6 next - hop 1 . 1 . 1 . 1 2 . 2 . 2 . 2 3 . 3 . 3 . 3
10,069
def set_ipv6_next_hop_load_share arr = config_get ( 'route_map' , 'set_ipv6_next_hop' , @get_args ) val = default_set_ipv6_next_hop_load_share arr . each do | str | next if str . empty? return true if str . include? ( 'load-share' ) end val end
set ipv6 default next - hop 1 . 1 . 1 . 1 2 . 2 . 2 . 2 3 . 3 . 3 . 3 load - share set ipv6 default next - hop load - share
10,070
def set_extcommunity_cost_set ( igp , pre ) str = '' if set_extcommunity_cost_device cpre = set_extcommunity_cost_pre_bestpath cigp = set_extcommunity_cost_igp cpre . each do | id , val | str . concat ( 'pre-bestpath ' + id . to_s + ' ' + val . to_s + ' ' ) end cigp . each do | id , val | str . concat ( 'igp ' + id . t...
set extcommunity cost igp 0 22 igp 3 23 set extcommunity cost pre - bestpath 1 222 pre - bestpath 2 54 set extcommunity cost pre - bestpath 1 222 pre - bestpath 2 54 igp 0 22
10,071
def anycast_gateway_mac mac = config_get ( 'overlay_global' , 'anycast_gateway_mac' ) mac . nil? || mac . empty? ? default_anycast_gateway_mac : mac . downcase end
anycast - gateway - mac
10,072
def encryption_key_set ( enctype , password ) password = Utils . add_quotes ( password ) if enctype == TACACS_SERVER_ENC_UNKNOWN if encryption_type != TACACS_SERVER_ENC_UNKNOWN config_set ( 'tacacs_server' , 'encryption' , state : 'no' , option : encryption_type , key : encryption_password ) end else config_set ( 'taca...
Set encryption type and password
10,073
def ingress_interface = ( list ) ingress_interface_cleanup @set_args [ :state ] = '' list . each do | intf , next_hop | @set_args [ :interface ] = intf @set_args [ :next ] = '' @set_args [ :nhop ] = '' unless next_hop == '' || next_hop == 'default' @set_args [ :next ] = 'next-hop' @set_args [ :nhop ] = next_hop end con...
only one next - hop is allowed per interface but due to nxos issues it allows more than one ; so the workaround is to clean up the current ingress intf and configure all of them again
10,074
def ensure_key_not_defined ( visited_keys ) fail ValueOverwriteError . new ( full_key ) if visited_keys . include? ( full_key ) visited_keys << full_key end
Fail if the key was already defined with a ValueOverwriteError
10,075
def save_stitch ( path , opts = { } ) return @browser . screenshot . save ( path ) if base64_capable? @options = opts @path = path calculate_dimensions return self . save ( @path ) if ( one_shot? || bug_shot? ) build_canvas gather_slices stitch_together @combined_screenshot . write @path end
Represents stitched together screenshot and writes to file .
10,076
def base64_canvas return self . base64 if base64_capable? output = nil return self . base64 if one_shot? || bug_shot? @browser . execute_script html2canvas_payload @browser . execute_script h2c_activator @browser . wait_until ( timeout : MAXIMUM_SCREENSHOT_GENERATION_WAIT_TIME ) { output = @browser . execute_script "re...
Employs html2canvas to produce a Base64 encoded string of a full page screenshot .
10,077
def setup_zk @zk = ZK . new ( @zkservers ) if @zkservers @zk . register ( redis_nodes_path ) { | event | handle_zk_event ( event ) } if @safe_mode @zk . on_expired_session { purge_clients } end @zk . on_connected { @zk . stat ( redis_nodes_path , :watch => true ) } @zk . stat ( redis_nodes_path , :watch => true ) updat...
Sets up the underlying ZooKeeper connection .
10,078
def handle_zk_event ( event ) update_znode_timestamp if event . node_created? || event . node_changed? build_clients elsif event . node_deleted? purge_clients @zk . stat ( redis_nodes_path , :watch => true ) else logger . error ( "Unknown ZK node event: #{event.inspect}" ) end ensure @zk . stat ( redis_nodes_path , :wa...
Handles a ZK event .
10,079
def dispatch ( method , * args , & block ) if @safe_mode && ! recently_heard_from_node_manager? build_clients end verify_supported! ( method ) tries = 0 begin client_for ( method ) . send ( method , * args , & block ) rescue * CONNECTIVITY_ERRORS => ex logger . error ( "Error while handling `#{method}` - #{ex.inspect}"...
Dispatches a redis operation to a master or slave .
10,080
def fetch_nodes data = @zk . get ( redis_nodes_path , :watch => true ) . first nodes = symbolize_keys ( decode ( data ) ) logger . debug ( "Fetched nodes: #{nodes.inspect}" ) nodes rescue Zookeeper :: Exceptions :: InheritedConnectionError , ZK :: Exceptions :: InterruptedSession => ex logger . debug { "Caught #{ex.cla...
Fetches the known redis nodes from ZooKeeper .
10,081
def new_clients_for ( * nodes ) nodes . map do | node | host , port = node . split ( ':' ) opts = { :host => host , :port => port } opts . update ( :db => @db ) if @db opts . update ( :password => @password ) if @password client = Redis . new ( @redis_client_options . merge ( opts ) ) if @namespace client = Redis :: Na...
Builds new Redis clients for the specified nodes .
10,082
def verify_role! ( node , role ) current_role = node . info [ 'role' ] if current_role . to_sym != role raise InvalidNodeRoleError . new ( address_for ( node ) , role , current_role ) end role end
Verifies the actual role for a redis node .
10,083
def nodes_changed? ( new_nodes ) return true if address_for ( @master ) != new_nodes [ :master ] return true if different? ( addresses_for ( @slaves ) , new_nodes [ :slaves ] ) false end
Determines if the currently known redis servers is different from the nodes returned by ZooKeeper .
10,084
def client_for ( method ) stack = Thread . current [ @current_client_key ] ||= [ ] client = if stack . last stack . last elsif @master_only master elsif REDIS_READ_OPS . include? ( method ) slave else master end stack << client client end
Acquires a client to use for the specified operation .
10,085
def parse_options ( options ) @zk , @zkservers = options . values_at ( :zk , :zkservers ) if [ @zk , @zkservers ] . all? || [ @zk , @zkservers ] . none? raise ArgumentError , 'must specify :zk or :zkservers' end @root_znode = options . fetch ( :znode_path , Util :: DEFAULT_ROOT_ZNODE_PATH ) @namespace = options [ :name...
Parses the configuration operations .
10,086
def make_slave! ( node ) perform_operation do | redis | unless slave_of? ( node ) redis . slaveof ( node . host , node . port ) logger . info ( "#{self} is now a slave of #{node}" ) wakeup end end end
Makes this node a slave of the given node .
10,087
def perform_operation redis = nil Timeout . timeout ( MAX_OP_WAIT_TIME ) do redis = new_client yield redis end rescue Exception => ex raise NodeUnavailableError , "#{ex.class}: #{ex.message}" , ex . backtrace ensure if redis begin redis . client . disconnect rescue Exception => ex raise NodeUnavailableError , "#{ex.cla...
Safely performs a redis operation within a given timeout window .
10,088
def setup_zk unless @zk @zk = ZK . new ( "#{@options[:zkservers]}#{@options[:chroot] || ''}" ) @zk . register ( manual_failover_path ) do | event | handle_manual_failover_update ( event ) end @zk . on_connected { @zk . stat ( manual_failover_path , :watch => true ) } end create_path ( @root_znode ) create_path ( curren...
Configures the ZooKeeper client .
10,089
def handle_unavailable ( node , snapshots ) return if @unavailable . include? ( node ) logger . info ( "Handling unavailable node: #{node}" ) @unavailable << node if node == @master logger . info ( "Demoting currently unavailable master #{node}." ) promote_new_master ( snapshots ) else @slaves . delete ( node ) end end
Handles an unavailable node .
10,090
def handle_available ( node , snapshots ) reconcile ( node ) return if @master == node || ( @master && @slaves . include? ( node ) ) logger . info ( "Handling available node: #{node}" ) if @master node . make_slave! ( @master ) @slaves << node else promote_new_master ( snapshots , node ) end @unavailable . delete ( nod...
Handles an available node .
10,091
def handle_syncing ( node , snapshots ) reconcile ( node ) if node . syncing_with_master? && node . prohibits_stale_reads? logger . info ( "Node #{node} not ready yet, still syncing with master." ) force_unavailable_slave ( node ) else handle_available ( node , snapshots ) end end
Handles a node that is currently syncing .
10,092
def handle_manual_failover ( node , snapshots ) return if @master == node logger . info ( "Handling manual failover" ) node . ping @slaves << @master if @master @slaves . delete ( node ) promote_new_master ( snapshots , node ) end
Handles a manual failover request to the given node .
10,093
def promote_new_master ( snapshots , node = nil ) delete_path ( redis_nodes_path ) @master = nil candidate = node || failover_strategy_candidate ( snapshots ) if candidate . nil? logger . error ( 'Failed to promote a new master, no candidate available.' ) else @slaves . delete ( candidate ) @unavailable . delete ( cand...
Promotes a new master .
10,094
def find_existing_master if data = @zk . get ( redis_nodes_path ) . first nodes = symbolize_keys ( decode ( data ) ) master = node_from ( nodes [ :master ] ) logger . info ( "Master from existing znode config: #{master || 'none'}" ) begin if master && master . slave? raise InvalidNodeRoleError . new ( master , :master ...
Seeds the initial node master from an existing znode config .
10,095
def node_from ( node_string ) return if node_string . nil? host , port = node_string . split ( ':' , 2 ) Node . new ( :host => host , :port => port , :password => @options [ :password ] ) end
Creates a Node instance from a string .
10,096
def guess_master ( nodes ) master_nodes = nodes . select { | node | node . master? } raise NoMasterError if master_nodes . empty? raise MultipleMastersError . new ( master_nodes ) if master_nodes . size > 1 master_nodes . first end
Searches for the master node .
10,097
def redirect_slaves_to ( node ) @slaves . dup . each do | slave | begin slave . make_slave! ( node ) rescue NodeUnavailableError logger . info ( "Failed to redirect unreachable slave #{slave} to #{node}" ) force_unavailable_slave ( slave ) end end end
Redirects all slaves to the specified node .
10,098
def reconcile ( node ) return if @master == node && node . master? return if @master && node . slave_of? ( @master ) logger . info ( "Reconciling node #{node}" ) if @master == node && ! node . master? node . make_master! return end if @master && ! node . slave_of? ( @master ) node . make_slave! ( @master ) end end
It s possible that a newly available node may have been restarted and completely lost its dynamically set run - time role by the node manager . This method ensures that the node resumes its role as determined by the manager .
10,099
def delete_path ( path ) @zk . delete ( path ) logger . info ( "Deleted ZK node #{path}" ) rescue ZK :: Exceptions :: NoNode => ex logger . info ( "Tried to delete missing znode: #{ex.inspect}" ) end
Deletes the znode path containing the redis nodes .