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



967
968
969
970
# File 'lib/dnsruby/resolver.rb', line 967

def initialize(parent)
  reset_attributes
  @parent=parent
end

Instance Method Details

#begin_validation(client_query_id, query_id, select_queue) ⇒ Object

Accept one answer for validation, without losing the total query deadline. The observer remains registered so ticks and this validator can finish the logical query. Competing attempts, including queued sends, no longer own it. MUST BE CALLED WITH THE PARENT MUTEX HELD.



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

def begin_validation(client_query_id, query_id, select_queue)
  @validation_queries[client_query_id] = query_id
  @timeouts[client_query_id][1].clear
  update_tick_deadline(client_query_id)
  SelectThread.instance.cancel_queries_for_queue(select_queue)
  @query_list[client_query_id][3].clear
end

#cancel_query(client_query_id, client_queue) ⇒ Object

Cancel only the nested discovery query owned by this synchronous waiter; never close a shared resolver or disturb unrelated callers.



1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
# File 'lib/dnsruby/resolver.rb', line 1145

def cancel_query(client_query_id, client_queue)
  @parent.single_res_mutex.synchronize do
    current = @query_list[client_query_id]
    if current && current[1].equal?(client_queue)
      stop_querying(client_query_id)
      @validation_queries.delete(client_query_id)
      @query_cache_scopes.delete(client_query_id)
      SelectThread.instance.remove_observer(current[2], self)
      @query_list.delete(client_query_id)
    end
  end
end

#close ⇒ Object

Close the Resolver. Unfinished queries are terminated with OtherResolvError.



1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
# File 'lib/dnsruby/resolver.rb', line 1131

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
    @parent.single_resolvers.compact.each(&:close)
  }
end

#decrement_resolver_priority(res) ⇒ Object

TO BE CALLED IN A SYNCHRONIZED BLOCK



1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
# File 'lib/dnsruby/resolver.rb', line 1483

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 && index < @parent.single_resolvers.length - 1
    @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



1495
1496
1497
1498
1499
1500
1501
1502
# File 'lib/dnsruby/resolver.rb', line 1495

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

#generate_timeouts ⇒ Object

:nodoc: all



1121
1122
1123
1124
1125
1126
1127
1128
# File 'lib/dnsruby/resolver.rb', line 1121

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
  #  All retry and query deadlines use the same monotonic clock.
  @parent.generate_timeouts(TransportClock.now).sort.to_h
end

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

:nodoc: all



1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
# File 'lib/dnsruby/resolver.rb', line 1395

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?(SocketEofResolvError) && _msg.header.opcode != OpCode.QUERY
    # An UPDATE or other operation may already have taken effect. An
    # ambiguous EOF ends the whole logical query, including other servers'
    # scheduled and outstanding attempts; do not replay it elsewhere.
    send_result_and_stop_querying(client_queue, client_query_id, select_queue, response, error)
    return
  end
  retryable_eof = error.kind_of?(SocketEofResolvError)
  if error.kind_of?(ResolvTimeout) || retryable_eof
    # A server can close a TCP connection before answering (RFC 7766
    # section 6.2.4). Keep the finite retry plan and original total deadline,
    # just as for a lost UDP packet; reconnecting must not add new retries.
    # An UPDATE may already have changed the server and must not be replayed
    # merely because its reply was lost.
    #    - 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
    begin_validation(client_query_id, query_id, select_queue)
    #  @TODO@ Does the client want notified at this point?
  elsif error.kind_of?(EncodeError) || error.kind_of?(RecursionLimitError)
    Dnsruby.log.debug{'Query cannot continue - sending error 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|
          if value.first.is_a?(Array)
            value.reject! { |res, _retry| res == resolver }
            timeouts[1].delete(key) if value.empty?
          elsif value.first == resolver
            timeouts[1].delete(key)
          end
        end
        update_tick_deadline(client_query_id)
      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.



1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
# File 'lib/dnsruby/resolver.rb', line 1304

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, 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 {
    current = @query_list[client_query_id]
    # An observer selected before completion can arrive after the caller
    # reuses its ID. Only the original logical query owns this queue.
    unless current && current[2].equal?(queue)
      Dnsruby.log.debug{'Ignoring response for completed query'}
      return
    end
    deadline, _retries, no_nameservers = @timeouts[client_query_id]
    if deadline && deadline <= TransportClock.now
      reason = no_nameservers ? 'Query timed out - no valid nameservers configured' : 'Query timed out'
      send_result_and_stop_querying(current[1], client_query_id, queue, nil,
        ResolvTimeout.new(reason))
      return
    end
    validation_query = @validation_queries[client_query_id]
    if validation_query
      # A response already accepted for validation owns completion. Errors
      # and already-queued answers from competing attempts cannot replace it.
      return unless event_type == Resolver::EventType::VALIDATED && validation_query == event_id
    elsif event_type == Resolver::EventType::VALIDATED
      return
    end
    _msg, _client_queue, _select_queue, outstanding = current
    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



1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
# File 'lib/dnsruby/resolver.rb', line 1504

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
  begin_validation(client_query_id, query_id, select_queue)
  #  @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



1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
# File 'lib/dnsruby/resolver.rb', line 1538

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



1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
# File 'lib/dnsruby/resolver.rb', line 1521

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



1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
# File 'lib/dnsruby/resolver.rb', line 1471

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 && index > 0
    @parent.single_resolvers.delete(res)
    @parent.single_resolvers.insert(index-1,res)
  end
  #       }
end

#next_tick_at ⇒ Object

Earliest retry or total query deadline, using the same lock as admission. The selector must call this outside its own lock.



1233
1234
1235
# File 'lib/dnsruby/resolver.rb', line 1233

def next_tick_at # :nodoc: all
  @parent.single_res_mutex.synchronize { @tick_deadlines.first_deadline }
end

#reset_attributes ⇒ Object

:nodoc: all



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

def reset_attributes # :nodoc: all
  #  data structures
  #       @mutex=Mutex.new
  @query_list = {}
  @timeouts = {}
  @tick_deadlines = DeadlineQueue.new
  @validation_queries = {}
  @transmission_budgets = {}
  @response_cache = Cache::ResolutionCache.new
  @query_cache_scopes = {}
end

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



1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
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
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
# File 'lib/dnsruby/resolver.rb', line 1019

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, nil, 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, nil, ArgumentError.new("Wrong type of msg passed to Dnsruby::Resolver# send_async - should have been Message, was #{msg.class}")])
    return
  end

  # According to RFC 6891, a UDP payload size >512 bytes requires an
  # EDNS OPT RR in the message.
  if @parent.udp_size > 512 && !msg.get_opt && !msg.send_raw && !msg.signed? && !msg.tsig
    TheLog.debug("Automatically adding EDNS OPT RR for udp_size=#{ @parent.udp_size }")
    msg.add_additional(Dnsruby::RR::OPT.new(@parent.udp_size))
  end

  begin
    # Encoding may sign the Message, even for this size check. Set the
    # header and EDNS options first so the signature covers the final query.
    sender = @parent.single_resolvers.first
    wire = sender ? sender.make_query_packet(msg) : msg.encode
    if wire.bytesize > 65_535
      raise EncodeError, 'DNS message exceeds the 65535-byte wire limit'
    end
  rescue EncodeError => err
    Dnsruby.log.error { "Can't encode " + msg.to_s + " : #{err}" }
    client_queue.push([client_query_id, nil, err])
    return
  end

  st = SelectThread.instance
  #  add to our data structures
  #       @mutex.synchronize{
  @parent.single_res_mutex.synchronize {
    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, nil, ArgumentError.new('Client query ID already in use')])
      return
    end
    scope = response_cache_scope(msg)
    control = QueryControl.current
    control&.check!
    if (cached = cached_completion(msg, scope))
      client_queue.push([client_query_id, *cached])
      return client_query_id
    end
    @query_cache_scopes[client_query_id] = scope
    outstanding = []
    @query_list[client_query_id]=[msg, client_queue, q, outstanding, control]
    @transmission_budgets[client_query_id] = SelectThread::TransmissionBudget.current || SelectThread::TransmissionBudget.new

    query_timeout = TransportClock.now + @parent.query_timeout
    if @parent.query_timeout == 0
      query_timeout = TransportClock.now + 31536000 # a year from now
    end
    retries = generate_timeouts
    # An explicitly empty nameserver list uses the ordinary query deadline
    # and completion path. No independent timer can publish a second result.
    no_nameservers = @parent.single_resolvers.empty?
    if no_nameservers && @parent.query_timeout == 0
      query_timeout = TransportClock.now + 1
    elsif retries.empty? && !no_nameservers
      # A caller may disable all attempts with retry_times=0. Complete
      # through the normal timeout path instead of leaving an orphan.
      query_timeout = TransportClock.now
    end
    query_timeout = [query_timeout, control&.deadline].compact.min
    @timeouts[client_query_id] = [query_timeout, retries, no_nameservers]
    update_tick_deadline(client_query_id)
    # Publish the observer together with its logical query. close must never
    # see a query whose selector ownership has not yet been registered.
    st.add_observer(q, self)
  }

  # Dispatch this query immediately, even while earlier queries are pending.
  # The same locked retry bookkeeping lets a concurrent selector tick win
  # safely, while socket I/O still happens after releasing the query lock.
  tick(client_query_id)
  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



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

def send_result(client_queue, client_query_id, select_queue, msg, error) # :nodoc: all
  cache_completion(client_query_id, msg, error)
  stop_querying(client_query_id)
  @validation_queries.delete(client_query_id)
  #  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])
rescue ClosedQueueError
  # The query and its observers are already removed. A closed client queue
  # must not stop the shared selector thread.
  Dnsruby.log.debug { "Discarding completion for closed client queue" }
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.



1162
1163
1164
# File 'lib/dnsruby/resolver.rb', line 1162

def send_result_and_stop_querying(client_queue, client_query_id, select_queue, msg, error) # :nodoc: all
  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



1169
1170
1171
1172
1173
# File 'lib/dnsruby/resolver.rb', line 1169

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

#tick(client_query_id = nil) ⇒ Object

This method is called when a retry or query deadline is due. 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



1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
# File 'lib/dnsruby/resolver.rb', line 1251

def tick(client_query_id = nil) # :nodoc: all
  #  Handle the tick
  #  Do we have any retries due to be sent yet?
  #       @mutex.synchronize{
  sends = []
  @parent.single_res_mutex.synchronize {
    time_now = TransportClock.now
    query_ids = client_query_id.nil? ? [] : [client_query_id]
    if client_query_id.nil?
      while (first = @tick_deadlines.first) && first[1] <= time_now
        query_ids << first[0]
        @tick_deadlines.delete(first[0])
      end
    end
    query_ids.each do |client_query_id|
      next unless @timeouts.key?(client_query_id)
      msg, client_queue, select_queue, outstanding, control = @query_list[client_query_id]
      query_timeout, timeouts, no_nameservers = @timeouts[client_query_id]
      if query_timeout <= time_now
        #  Time the query out through the same exactly-once completion path.
        reason = no_nameservers ? 'Query timed out - no valid nameservers configured' : 'Query timed out'
        send_result_and_stop_querying(client_queue, client_query_id, select_queue, nil,
            ResolvTimeout.new(reason))
        next
      end
      # The finite retry plan is ordered once when admitted. Hash deletion
      # retains that order, so no unrelated retry plan needs to be sorted.
      while (timeout = timeouts.each_key.first) && timeout <= time_now
        attempts = timeouts.delete(timeout)
        attempts = [attempts] unless attempts.first.is_a?(Array)
        attempts.each do |res, retry_count|
          id = [res, msg, client_query_id, retry_count]
          Dnsruby.log.debug("Sending msg to #{res.server}")
          outstanding.push(id)
          # A query keeps its original retry plan after reconfiguration.
          # Retired senders must not create unreachable reusable sockets.
          retired = !@parent.single_resolvers.include?(res)
          operation = res.prepare_send_async(msg, select_queue, id, retired, control,
            (@transmission_budgets[client_query_id] ||= SelectThread::TransmissionBudget.new))
          sends << operation if operation
        end
      end
      update_tick_deadline(client_query_id)
    end
  }
  sends.each(&:call)
end

#validation_deadline(select_queue, query_id) ⇒ Object

Called outside the selector lock. A completed or replaced transaction cannot start validation, and validation keeps the original query deadline.



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

def validation_deadline(select_queue, query_id)
  client_query_id = query_id[2]
  @parent.single_res_mutex.synchronize do
    current = @query_list[client_query_id]
    if current && current[2].equal?(select_queue) && @validation_queries[client_query_id] == query_id
      @timeouts[client_query_id][0]
    end
  end
end

#validation_transmission_budget(select_queue, query_id) ⇒ Object



1199
1200
1201
1202
1203
1204
1205
1206
1207
# File 'lib/dnsruby/resolver.rb', line 1199

def validation_transmission_budget(select_queue, query_id)
  client_query_id = query_id[2]
  @parent.single_res_mutex.synchronize do
    current = @query_list[client_query_id]
    if current && current[2].equal?(select_queue) && @validation_queries[client_query_id] == query_id
      @transmission_budgets[client_query_id]
    end
  end
end