Class: Dnsruby::ResolverRuby

Inherits:
Object
  • Object
show all
Defined in:
lib/dnsruby/resolver.rb

Overview

This class implements the I/O using pure Ruby, with no dependencies.

Support for EventMachine has been deprecated.

Instance Method Summary collapse

Constructor Details

#initialize(parent) ⇒ ResolverRuby

:nodoc: all



852
853
854
855
# File 'lib/dnsruby/resolver.rb', line 852

def initialize(parent)
  reset_attributes
  @parent=parent
end

Instance Method Details

#closeObject

Close the Resolver. Unfinished queries are terminated with OtherResolvError.



938
939
940
941
942
943
944
945
946
947
# File 'lib/dnsruby/resolver.rb', line 938

def close
  #       @mutex.synchronize {
  @parent.single_res_mutex.synchronize {
    @query_list.each do |client_query_id, values|
     _msg, client_queue, q, _outstanding = values
      send_result_and_stop_querying(client_queue, client_query_id, q, nil,
          OtherResolvError.new('Resolver closing!'))
    end
  }
end

#decrement_resolver_priority(res) ⇒ Object

TO BE CALLED IN A SYNCHRONIZED BLOCK



1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
# File 'lib/dnsruby/resolver.rb', line 1179

def decrement_resolver_priority(res)
  TheLog.debug("Decrementing resolver priority for #{res.server}\n")
  #       @parent.single_res_mutex.synchronize {
  index = @parent.single_resolvers.index(res)
  if index < @parent.single_resolvers.length
    @parent.single_resolvers.delete(res)
    @parent.single_resolvers.insert(index+1,res)
  end
  #       }
end

#demote_resolver(res) ⇒ Object

TO BE CALLED IN A SYNCHRONIZED BLOCK



1191
1192
1193
1194
1195
1196
1197
# File 'lib/dnsruby/resolver.rb', line 1191

def demote_resolver(res)
  TheLog.debug("Demoting resolver priority for #{res.server} to bottom\n")
  #       @parent.single_res_mutex.synchronize {
  @parent.single_resolvers.delete(res)
  @parent.single_resolvers.push(res)
  #       }
end

#generate_timeoutsObject

:nodoc: all



928
929
930
931
932
933
934
935
# File 'lib/dnsruby/resolver.rb', line 928

def generate_timeouts # :nodoc: all
  #  Create the timeouts for the query from the retry_times and retry_delay attributes.
  #  These are created at the same time in case the parameters change during the life of the query.
  #
  #  These should be absolute, rather than relative
  #  The first value should be Time.now[
  @parent.generate_timeouts(Time.now)
end

#handle_error_response(select_queue, query_id, error, response) ⇒ Object

:nodoc: all



1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
# File 'lib/dnsruby/resolver.rb', line 1107

def handle_error_response(select_queue, query_id, error, response) # :nodoc: all
  #  Handle an error
  #       @mutex.synchronize{
  Dnsruby.log.debug{"handling error #{error.class}, #{error}"}
  #  Check what sort of error it was :
  resolver, _msg, client_query_id, _retry_count = query_id
  _msg, client_queue, select_queue, outstanding = @query_list[client_query_id]
  if error.kind_of?(ResolvTimeout)
    #    - if it was a timeout, then check which number it was, and how many retries are expected on that server
    #        - if it was the last retry, on the last server, then return a timeout to the client (and clean up)
    #        - otherwise, continue
    #  Do we have any more packets to send to this resolver?

    decrement_resolver_priority(resolver)
    timeouts = @timeouts[client_query_id]
    if outstanding.empty? && timeouts && timeouts[1].values.empty?
      Dnsruby.log.debug{'Sending timeout to client'}
      send_result_and_stop_querying(client_queue, client_query_id, select_queue, response, error)
    end
  elsif error.kind_of?(NXDomain)
    #    - if it was an NXDomain, then return that to the client, and stop all new queries (and clean up)
    #         send_result_and_stop_querying(client_queue, client_query_id, select_queue, response, error)
    increment_resolver_priority(resolver) unless response.cached
    stop_querying(client_query_id)
    #  @TODO@ Does the client want notified at this point?
  elsif error.kind_of?(EncodeError)
    Dnsruby.log.debug{'Encode error - sending to client'}
    send_result_and_stop_querying(client_queue, client_query_id, select_queue, response, error)
  else
    #    - if it was any other error, then remove that server from the list for that query
    #    If a Too Many Open Files error, then don't remove, but let retry work.
    timeouts = @timeouts[client_query_id]
    unless error.to_s =~ /Errno::EMFILE/
      Dnsruby.log.debug{"Removing #{resolver.server} from resolver list for this query"}
      if timeouts
        timeouts[1].each do |key, value|
          res = value[0]
          if res == resolver
            timeouts[1].delete(key)
          end
        end
      end
      #  Also stick it to the back of the list for future queries
      demote_resolver(resolver)
    else
      Dnsruby.log.debug("NOT Removing #{resolver.server} due to Errno::EMFILE")
    end
    #         - if it was the last server, then return an error to the client (and clean up)
    if outstanding.empty? && ((!timeouts) || (timeouts && timeouts[1].values.empty?))
      #           if outstanding.empty?
      Dnsruby.log.debug{'Sending error to client'}
      send_result_and_stop_querying(client_queue, client_query_id, select_queue, response, error)
    end
  end
  #  @TODO@ If we're still sending packets for this query, but none are outstanding, then
  #  jumpstart the next query?
  #       }
end

#handle_queue_event(queue, id) ⇒ Object

This method is called by the SelectThread (in the select thread) when the queue has a new item on it.

The queue interface is used to separate producer/consumer threads, but we're using it here in one thread.
It's probably a good idea to create a new "worker thread" to take items from the select thread queue and
call this method in the worker thread.


1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
# File 'lib/dnsruby/resolver.rb', line 1030

def handle_queue_event(queue, id) # :nodoc: all
  #  Time to process a new queue event.
  #  If we get a callback for an ID we don't know about, don't worry -
  #  just ignore it. It may be for a query we've already completed.
  #
  #  So, get the next response from the queue (presuming there is one!)
  #
  #  @TODO@ Tick could poll the queue and then call this method if needed - no need for observer interface.
  #  @TODO@ Currently, tick and handle_queue_event called from select_thread - could have thread chuck events in to tick_queue. But then, clients would have to call in on other thread!
  #
  #  So - two types of response :
  #  1) we've got a coherent response (or error) - stop sending more packets for that query!
  #  2) we've validated the response - it's ready to be sent to the client
  #
  #  so need two more methods :
  #   handleValidationResponse : basically calls send_result_and_stop_querying and
  #   handleValidationError : does the same as handleValidationResponse, but for errors
  #  can leave handleError alone
  #  but need to change handleResponse to stop sending, rather than send_result_and_stop_querying.
  #
  #  @TODO@ Also, we could really do with a MaxValidationTimeout - if validation not OK within
  #  this time, then raise Timeout (and stop validation)?
  #
  #  @TODO@ Also, should there be some facility to stop validator following same chain
  #  concurrently?
  #
  #  @TODO@ Also, should have option to speak only to configured resolvers (not follow authoritative chain)
  #
  if queue.empty?
    Dnsruby.log_and_raise('Severe internal error - Queue empty in handle_queue_event')
  end
  event_id, event_type, response, error = queue.pop
  #  We should remove this packet from the list of outstanding packets for this query
  _resolver, _msg, client_query_id, _retry_count = id
  if id != event_id
    Dnsruby.log_and_raise("Serious internal error!! #{id} expected, #{event_id} received")
  end
  #       @mutex.synchronize{
  @parent.single_res_mutex.synchronize {
    if @query_list[client_query_id] == nil
      #           print "Dead query response - ignoring\n"
      Dnsruby.log.debug{'Ignoring response for dead query'}
      return
    end
    _msg, _client_queue, _select_queue, outstanding = @query_list[client_query_id]
    if event_type == Resolver::EventType::RECEIVED ||
          event_type == Resolver::EventType::ERROR
      unless outstanding.include?(id)
        Dnsruby.log.error("Query id not on outstanding list! #{outstanding.length} items. #{id} not on #{outstanding}")
      end
      outstanding.delete(id)
    end
    #       }
    if event_type == Resolver::EventType::RECEIVED
      #       if (event.kind_of?(Exception))
      if error
        handle_error_response(queue, event_id, error, response)
      else # if event.kind_of?(Message)
        handle_response(queue, event_id, response)
        #       else
        #         Dnsruby.log.error('Random object #{event.class} returned through queue to Resolver')
      end
    elsif event_type == Resolver::EventType::VALIDATED
      if error
        handle_validation_error(queue, event_id, error, response)
      else
        handle_validation_response(queue, event_id, response)
      end
    elsif event_type == Resolver::EventType::ERROR
      handle_error_response(queue, event_id, error, response)
    else
      #           print "ERROR - UNKNOWN EVENT TYPE IN RESOLVER : #{event_type}\n"
      TheLog.error("ERROR - UNKNOWN EVENT TYPE IN RESOLVER : #{event_type}")
    end
  }
end

#handle_response(select_queue, query_id, response) ⇒ Object

:nodoc: all



1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
# File 'lib/dnsruby/resolver.rb', line 1199

def handle_response(select_queue, query_id, response) # :nodoc: all
  #  Handle a good response
  #  Should also stick resolver more to the front of the list for future queries
  Dnsruby.log.debug('Handling good response')
  resolver, _msg, client_query_id, _retry_count = query_id
  increment_resolver_priority(resolver) unless response.cached
  #       @mutex.synchronize{
  _query, _client_queue, s_queue, _outstanding = @query_list[client_query_id]
  if s_queue != select_queue
    Dnsruby.log_and_raise("Serious internal error : expected select queue #{s_queue}, got #{select_queue}")
  end
  stop_querying(client_query_id)
  #  @TODO@ Does the client want notified at this point?
  #         client_queue.push([client_query_id, Resolver::EventType::RECEIVED, msg, nil])
  #       }
end

#handle_validation_error(select_queue, query_id, error, response) ⇒ Object



1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
# File 'lib/dnsruby/resolver.rb', line 1233

def handle_validation_error(select_queue, query_id, error, response)
  _resolver, _msg, client_query_id, _retry_count = query_id
  _query, client_queue, s_queue, _outstanding = @query_list[client_query_id]
  if s_queue != select_queue
    Dnsruby.log_and_raise("Serious internal error : expected select queue #{s_queue}, got #{select_queue}")
  end
  #       For some errors, we immediately send result. For others, should we retry?
  #       Either :
  #                 handle_error_response(queue, event_id, error, response)
  #                 Or:
  send_result(client_queue, client_query_id, select_queue, response, error)
  #
  #
end

#handle_validation_response(select_queue, query_id, response) ⇒ Object

:nodoc: all



1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
# File 'lib/dnsruby/resolver.rb', line 1216

def handle_validation_response(select_queue, query_id, response) # :nodoc: all
  _resolver, _msg, client_query_id, _retry_count = query_id
  #       @mutex.synchronize {
  _query, client_queue, s_queue, _outstanding = @query_list[client_query_id]
  if s_queue != select_queue
    Dnsruby.log_and_raise("Serious internal error : expected select queue #{s_queue}, got #{select_queue}")
  end
  if response.rcode == RCode.NXDOMAIN
    send_result(client_queue, client_query_id, select_queue, response, NXDomain.new)
  else
    #  @TODO@ Was there an error validating? Should we raise an exception for certain security levels?
    #  This should be configurable by the client.
    send_result(client_queue, client_query_id, select_queue, response, nil)
    #       }
  end
end

#increment_resolver_priority(res) ⇒ Object

TO BE CALLED IN A SYNCHRONIZED BLOCK



1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
# File 'lib/dnsruby/resolver.rb', line 1167

def increment_resolver_priority(res)
  TheLog.debug("Incrementing resolver priority for #{res.server}\n")
  #       @parent.single_res_mutex.synchronize {
  index = @parent.single_resolvers.index(res)
  if index > 0
    @parent.single_resolvers.delete(res)
    @parent.single_resolvers.insert(index-1,res)
  end
  #       }
end

#reset_attributesObject

:nodoc: all



856
857
858
859
860
861
# File 'lib/dnsruby/resolver.rb', line 856

def reset_attributes # :nodoc: all
  #  data structures
  #       @mutex=Mutex.new
  @query_list = {}
  @timeouts = {}
end

#send_async(msg, client_queue, client_query_id = nil) ⇒ Object



862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
# File 'lib/dnsruby/resolver.rb', line 862

def send_async(msg, client_queue, client_query_id=nil)
  #  This is the whole point of the Resolver class.
  #  We want to use multiple SingleResolvers to run a query.
  #  So we kick off a system with select_thread where we send
  #  a query with a queue, but log ourselves as observers for that
  #  queue. When a new response is pushed on to the queue, then the
  #  select thread will call this class' handler method IN THAT THREAD.
  #  When the final response is known, this class then sticks it in
  #  to the client queue.

  q = Queue.new
  if client_query_id.nil?
    client_query_id = Time.now + rand(10000)
  end

  unless client_queue.kind_of?(Queue)
    Dnsruby.log_and_raise('Wrong type for client_queue in Resolver# send_async')
    #  @TODO@ Handle different queue tuples - push this to generic send_error method
    client_queue.push([client_query_id, ArgumentError.new('Wrong type of client_queue passed to Dnsruby::Resolver# send_async - should have been Queue, was #{client_queue.class}')])
    return
  end

  unless msg.kind_of?Message
    Dnsruby.log.error{'Wrong type for msg in Resolver# send_async'}
    #  @TODO@ Handle different queue tuples - push this to generic send_error method
    client_queue.push([client_query_id, ArgumentError.new("Wrong type of msg passed to Dnsruby::Resolver# send_async - should have been Message, was #{msg.class}")])
    return
  end

  begin
    msg.encode
  rescue EncodeError => err
    Dnsruby.log.error { "Can't encode " + msg.to_s + " : #{err}" }
    client_queue.push([client_query_id, err])
    return
  end

  tick_needed = false
  #  add to our data structures
  #       @mutex.synchronize{
  @parent.single_res_mutex.synchronize {
    tick_needed = true if @query_list.empty?
    if @query_list.has_key?(client_query_id)
      Dnsruby.log.error("Duplicate query id requested (#{client_query_id}")
      #  @TODO@ Handle different queue tuples - push this to generic send_error method
      client_queue.push([client_query_id, ArgumentError.new('Client query ID already in use')])
      return
    end
    outstanding = []
    @query_list[client_query_id]=[msg, client_queue, q, outstanding]

    query_timeout = Time.now + @parent.query_timeout
    if @parent.query_timeout == 0
      query_timeout = Time.now + 31536000 # a year from now
    end
    @timeouts[client_query_id] = [query_timeout, generate_timeouts]
  }

  #  Now do querying stuff using SingleResolver
  #  All this will be handled by the tick method (if we have 0 as the first timeout)
  st = SelectThread.instance
  st.add_observer(q, self)
  tick if tick_needed
  client_query_id
end

#send_result(client_queue, client_query_id, select_queue, msg, error) ⇒ Object

MUST BE CALLED IN A SYNCHRONIZED BLOCK!

Sends the result to the client's queue, and removes the queue observer from the select thread


968
969
970
971
972
973
974
975
976
977
978
979
# File 'lib/dnsruby/resolver.rb', line 968

def send_result(client_queue, client_query_id, select_queue, msg, error) # :nodoc: all
  stop_querying(client_query_id)  # @TODO@ !
  #  We might still get some callbacks, which we should ignore
  st = SelectThread.instance
  st.remove_observer(select_queue, self)
  #       @mutex.synchronize{
  #  Remove the query from all of the data structures
  @query_list.delete(client_query_id)
  #       }
  #  Return the response to the client
  client_queue.push([client_query_id, msg, error])
end

#send_result_and_stop_querying(client_queue, client_query_id, select_queue, msg, error) ⇒ Object

MUST BE CALLED IN A SYNCHRONIZED BLOCK!

Send the result back to the client, and close the socket for that query by removing
the query from the select thread.


953
954
955
956
# File 'lib/dnsruby/resolver.rb', line 953

def send_result_and_stop_querying(client_queue, client_query_id, select_queue, msg, error) # :nodoc: all
  stop_querying(client_query_id)
  send_result(client_queue, client_query_id, select_queue, msg, error)
end

#stop_querying(client_query_id) ⇒ Object

MUST BE CALLED IN A SYNCHRONIZED BLOCK!

Stops send any more packets for a client-level query


961
962
963
# File 'lib/dnsruby/resolver.rb', line 961

def stop_querying(client_query_id) # :nodoc: all
  @timeouts.delete(client_query_id)
end

#tickObject

This method is called twice a second from the select loop, in the select thread.

It should arguably be called from another worker thread... (which also handles the queue)
Each tick, we check if any timeouts have occurred. If so, we take the appropriate action :
Return a timeout to the client, or send a new query


985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
# File 'lib/dnsruby/resolver.rb', line 985

def tick # :nodoc: all
  #  Handle the tick
  #  Do we have any retries due to be sent yet?
  #       @mutex.synchronize{
  @parent.single_res_mutex.synchronize {
    time_now = Time.now
    @timeouts.keys.each do |client_query_id|
      msg, client_queue, select_queue, outstanding = @query_list[client_query_id]
      query_timeout, timeouts = @timeouts[client_query_id]
      if query_timeout < Time.now
        #  Time the query out
        send_result_and_stop_querying(client_queue, client_query_id, select_queue, nil,
            ResolvTimeout.new('Query timed out'))
        next
      end
      timeouts_done = []
      timeouts.keys.sort.each do |timeout|
        if timeout < time_now
          #  Send the next query
          res, retry_count = timeouts[timeout]
          id = [res, msg, client_query_id, retry_count]
          Dnsruby.log.debug("Sending msg to #{res.server}")
          #  We should keep a list of the queries which are outstanding
          outstanding.push(id)
          timeouts_done.push(timeout)
          timeouts.delete(timeout)

          #  Pick a new QID here @TODO@ !!!
          #               msg.header.id = rand(65535);
          #               print "New query : #{new_msg}\n"
          res.send_async(msg, select_queue, id)
        else
          break
        end
      end
      timeouts_done.each { |t| timeouts.delete(t) }
    end
  }
end