Class: Fluent::Plugin::ForwardOutput::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/fluent/plugin/out_forward.rb

Direct Known Subclasses

NoneHeartbeatNode

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sender, server, failure:) ⇒ Node

Returns a new instance of Node.



510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
# File 'lib/fluent/plugin/out_forward.rb', line 510

def initialize(sender, server, failure:)
  @sender = sender
  @log = sender.log
  @compress = sender.compress

  @name = server.name
  @host = server.host
  @port = server.port
  @weight = server.weight
  @standby = server.standby
  @failure = failure
  @available = true
  @state = nil

  # @hostname is used for certificate verification & TLS SNI
  host_is_hostname = !(IPAddr.new(@host) rescue false)
  @hostname = case
              when host_is_hostname then @host
              when @name then @name
              else nil
              end

  @usock = nil

  @username = server.username
  @password = server.password
  @shared_key = server.shared_key || (sender.security && sender.security.shared_key) || ""
  @shared_key_salt = generate_salt
  @shared_key_nonce = ""

  @unpacker = Fluent::Engine.msgpack_unpacker

  @resolved_host = nil
  @resolved_time = 0
  @resolved_once = false
end

Instance Attribute Details

#availableObject (readonly)

for test



551
552
553
# File 'lib/fluent/plugin/out_forward.rb', line 551

def available
  @available
end

#failureObject (readonly)

for test



551
552
553
# File 'lib/fluent/plugin/out_forward.rb', line 551

def failure
  @failure
end

#hostObject (readonly)

Returns the value of attribute host.



549
550
551
# File 'lib/fluent/plugin/out_forward.rb', line 549

def host
  @host
end

#nameObject (readonly)

Returns the value of attribute name.



549
550
551
# File 'lib/fluent/plugin/out_forward.rb', line 549

def name
  @name
end

#portObject (readonly)

Returns the value of attribute port.



549
550
551
# File 'lib/fluent/plugin/out_forward.rb', line 549

def port
  @port
end

#sockaddrObject (readonly)

used by on_heartbeat



550
551
552
# File 'lib/fluent/plugin/out_forward.rb', line 550

def sockaddr
  @sockaddr
end

#standbyObject (readonly)

Returns the value of attribute standby.



549
550
551
# File 'lib/fluent/plugin/out_forward.rb', line 549

def standby
  @standby
end

#stateObject (readonly)

Returns the value of attribute state.



549
550
551
# File 'lib/fluent/plugin/out_forward.rb', line 549

def state
  @state
end

#usockObject

Returns the value of attribute usock.



547
548
549
# File 'lib/fluent/plugin/out_forward.rb', line 547

def usock
  @usock
end

#weightObject (readonly)

Returns the value of attribute weight.



549
550
551
# File 'lib/fluent/plugin/out_forward.rb', line 549

def weight
  @weight
end

Instance Method Details

#available?Boolean

Returns:

  • (Boolean)


557
558
559
# File 'lib/fluent/plugin/out_forward.rb', line 557

def available?
  @available
end

#check_helo(message) ⇒ Object



755
756
757
758
759
760
761
762
763
764
765
766
# File 'lib/fluent/plugin/out_forward.rb', line 755

def check_helo(message)
  @log.debug "checking helo"
  # ['HELO', options(hash)]
  unless message.size == 2 && message[0] == 'HELO'
    return false
  end
  opts = message[1] || {}
  # make shared_key_check failed (instead of error) if protocol version mismatch exist
  @shared_key_nonce = opts['nonce'] || ''
  @authentication = opts['auth'] || ''
  true
end

#check_pong(message) ⇒ Object



787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
# File 'lib/fluent/plugin/out_forward.rb', line 787

def check_pong(message)
  @log.debug "checking pong"
  # ['PONG', bool(authentication result), 'reason if authentication failed',
  #  self_hostname, sha512\_hex(salt + self_hostname + nonce + sharedkey)]
  unless message.size == 5 && message[0] == 'PONG'
    return false, 'invalid format for PONG message'
  end
  _pong, auth_result, reason, hostname, shared_key_hexdigest = message

  unless auth_result
    return false, 'authentication failed: ' + reason
  end

  if hostname == @sender.security.self_hostname
    return false, 'same hostname between input and output: invalid configuration'
  end

  clientside = Digest::SHA512.new.update(@shared_key_salt).update(hostname).update(@shared_key_nonce).update(@shared_key).hexdigest
  unless shared_key_hexdigest == clientside
    return false, 'shared key mismatch'
  end

  return true, nil
end

#disable!Object



561
562
563
# File 'lib/fluent/plugin/out_forward.rb', line 561

def disable!
  @available = false
end

#establish_connection(sock) ⇒ Object



569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
# File 'lib/fluent/plugin/out_forward.rb', line 569

def establish_connection(sock)
  while available? && @state != :established
    begin
      # TODO: On Ruby 2.2 or earlier, read_nonblock doesn't work expectedly.
      # We need rewrite around here using new socket/server plugin helper.
      buf = sock.read_nonblock(@sender.read_length)
      if buf.empty?
        sleep @sender.read_interval
        next
      end
      @unpacker.feed_each(buf) do |data|
        on_read(sock, data)
      end
    rescue IO::WaitReadable
      # If the exception is Errno::EWOULDBLOCK or Errno::EAGAIN, it is extended by IO::WaitReadable.
      # So IO::WaitReadable can be used to rescue the exceptions for retrying read_nonblock.
      # http://docs.ruby-lang.org/en/2.3.0/IO.html#method-i-read_nonblock
      sleep @sender.read_interval unless @state == :established
    rescue SystemCallError => e
      @log.warn "disconnected by error", host: @host, port: @port, error: e
      disable!
      break
    rescue EOFError
      @log.warn "disconnected", host: @host, port: @port
      disable!
      break
    end
  end
end

#generate_pingObject



768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
# File 'lib/fluent/plugin/out_forward.rb', line 768

def generate_ping
  @log.debug "generating ping"
  # ['PING', self_hostname, sharedkey\_salt, sha512\_hex(sharedkey\_salt + self_hostname + nonce + shared_key),
  #  username || '', sha512\_hex(auth\_salt + username + password) || '']
  shared_key_hexdigest = Digest::SHA512.new.update(@shared_key_salt)
    .update(@sender.security.self_hostname)
    .update(@shared_key_nonce)
    .update(@shared_key)
    .hexdigest
  ping = ['PING', @sender.security.self_hostname, @shared_key_salt, shared_key_hexdigest]
  if !@authentication.empty?
    password_hexdigest = Digest::SHA512.new.update(@authentication).update(@username).update(@password).hexdigest
    ping.push(@username, password_hexdigest)
  else
    ping.push('','')
  end
  ping
end

#generate_saltObject



751
752
753
# File 'lib/fluent/plugin/out_forward.rb', line 751

def generate_salt
  SecureRandom.hex(16)
end

#heartbeat(detect = true) ⇒ Object



739
740
741
742
743
744
745
746
747
748
749
# File 'lib/fluent/plugin/out_forward.rb', line 739

def heartbeat(detect=true)
  now = Time.now.to_f
  @failure.add(now)
  if detect && !@available && @failure.sample_size > @sender.recover_sample_size
    @available = true
    @log.warn "recovered forwarding server '#{@name}'", host: @host, port: @port
    true
  else
    nil
  end
end

#on_read(sock, data) ⇒ Object



812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
# File 'lib/fluent/plugin/out_forward.rb', line 812

def on_read(sock, data)
  @log.trace __callee__

  case @state
  when :helo
    unless check_helo(data)
      @log.warn "received invalid helo message from #{@name}"
      disable! # shutdown
      return
    end
    sock.write(generate_ping.to_msgpack)
    @state = :pingpong
  when :pingpong
    succeeded, reason = check_pong(data)
    unless succeeded
      @log.warn "connection refused to #{@name}: #{reason}"
      disable! # shutdown
      return
    end
    @state = :established
    @log.debug "connection established", host: @host, port: @port
  else
    raise "BUG: unknown session state: #{@state}"
  end
end

#resolved_hostObject



680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
# File 'lib/fluent/plugin/out_forward.rb', line 680

def resolved_host
  case @sender.expire_dns_cache
  when 0
    # cache is disabled
    resolve_dns!

  when nil
    # persistent cache
    @resolved_host ||= resolve_dns!

  else
    now = Fluent::Engine.now
    rh = @resolved_host
    if !rh || now - @resolved_time >= @sender.expire_dns_cache
      rh = @resolved_host = resolve_dns!
      @resolved_time = now
    end
    rh
  end
end

#send_data(tag, chunk) ⇒ Object



630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
# File 'lib/fluent/plugin/out_forward.rb', line 630

def send_data(tag, chunk)
  sock = @sender.create_transfer_socket(resolved_host, port, @hostname)
  begin
    send_data_actual(sock, tag, chunk)
  rescue
    sock.close rescue nil
    raise
  end

  if @sender.require_ack_response
    return sock # to read ACK from socket
  end

  sock.close_write rescue nil
  sock.close rescue nil
  heartbeat(false)
  nil
end

#send_data_actual(sock, tag, chunk) ⇒ Object



599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
# File 'lib/fluent/plugin/out_forward.rb', line 599

def send_data_actual(sock, tag, chunk)
  @state = @sender.security ? :helo : :established
  if @state != :established
    establish_connection(sock)
  end

  unless available?
    raise ConnectionClosedError, "failed to establish connection with node #{@name}"
  end

  option = { 'size' => chunk.size, 'compressed' => @compress }
  option['chunk'] = Base64.encode64(chunk.unique_id) if @sender.require_ack_response

  # https://github.com/fluent/fluentd/wiki/Forward-Protocol-Specification-v1#packedforward-mode
  # out_forward always uses str32 type for entries.
  # str16 can store only 64kbytes, and it should be much smaller than buffer chunk size.

  tag = tag.dup.force_encoding(Encoding::UTF_8)

  sock.write @sender.forward_header                    # array, size=3
  sock.write tag.to_msgpack                            # 1. tag: String (str)
  chunk.open(compressed: @compress) do |chunk_io|
    entries = [0xdb, chunk_io.size].pack('CN')
    sock.write entries.force_encoding(Encoding::UTF_8) # 2. entries: String (str32)
    IO.copy_stream(chunk_io, sock)                     #    writeRawBody(packed_es)
  end
  sock.write option.to_msgpack                         # 3. option: Hash(map)

  # TODO: use bin32 for non-utf8 content(entries) when old msgpack-ruby (0.5.x or earlier) not supported
end

#send_heartbeatObject

FORWARD_TCP_HEARTBEAT_DATA = FORWARD_HEADER + ”.to_msgpack + [].to_msgpack



650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
# File 'lib/fluent/plugin/out_forward.rb', line 650

def send_heartbeat
  begin
    dest_addr = resolved_host
    @resolved_once = true
  rescue ::SocketError => e
    if !@resolved_once && @sender.ignore_network_errors_at_startup
      @log.warn "failed to resolve node name in heartbeating", server: @name || @host, error: e
      return
    end
    raise
  end

  case @sender.heartbeat_type
  when :transport
    @sender.create_transfer_socket(dest_addr, port, @hostname) do |sock|
      ## don't send any data to not cause a compatibility problem
      # sock.write FORWARD_TCP_HEARTBEAT_DATA

      # successful tcp connection establishment is considered as valid heartbeat
      heartbeat(true)
    end
  when :udp
    @usock.send "\0", 0, Socket.pack_sockaddr_in(@port, resolved_host)
  when :none # :none doesn't use this class
    raise "BUG: heartbeat_type none must not use Node"
  else
    raise "BUG: unknown heartbeat_type '#{@sender.heartbeat_type}'"
  end
end

#standby?Boolean

Returns:

  • (Boolean)


565
566
567
# File 'lib/fluent/plugin/out_forward.rb', line 565

def standby?
  @standby
end

#tickObject



709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
# File 'lib/fluent/plugin/out_forward.rb', line 709

def tick
  now = Time.now.to_f
  if !@available
    if @failure.hard_timeout?(now)
      @failure.clear
    end
    return nil
  end

  if @failure.hard_timeout?(now)
    @log.warn "detached forwarding server '#{@name}'", host: @host, port: @port, hard_timeout: true
    @available = false
    @resolved_host = nil  # expire cached host
    @failure.clear
    return true
  end

  if @sender.phi_failure_detector
    phi = @failure.phi(now)
    if phi > @sender.phi_threshold
      @log.warn "detached forwarding server '#{@name}'", host: @host, port: @port, phi: phi, phi_threshold: @sender.phi_threshold
      @available = false
      @resolved_host = nil  # expire cached host
      @failure.clear
      return true
    end
  end
  false
end

#validate_host_resolution!Object



553
554
555
# File 'lib/fluent/plugin/out_forward.rb', line 553

def validate_host_resolution!
  resolved_host
end