Class: Net::Knocker::Peer

Inherits:
Object
  • Object
show all
Extended by:
Env
Defined in:
lib/net/knocker/peer.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Env

debug, debugging?, env_secret, error, http_client, info, log, should_omit?, ssl_certificate, ssl_key, url, var_names, warn

Constructor Details

#initialize(pid) ⇒ Peer

Returns a new instance of Peer.



11
12
13
14
15
# File 'lib/net/knocker/peer.rb', line 11

def initialize(pid)
  @pid = pid
  @exe ||= Pathname("/proc/#{pid}/exe").realpath
  @environ_path ||= Pathname("/proc/#{pid}/environ")
end

Instance Attribute Details

#environ_pathObject (readonly)

Returns the value of attribute environ_path.



9
10
11
# File 'lib/net/knocker/peer.rb', line 9

def environ_path
  @environ_path
end

#exeObject (readonly)

Returns the value of attribute exe.



9
10
11
# File 'lib/net/knocker/peer.rb', line 9

def exe
  @exe
end

#pidObject (readonly)

Returns the value of attribute pid.



9
10
11
# File 'lib/net/knocker/peer.rb', line 9

def pid
  @pid
end

Class Method Details

.any?(&block) ⇒ Boolean

Returns:

  • (Boolean)


57
58
59
# File 'lib/net/knocker/peer.rb', line 57

def self.any?(&block)
  peers.any?(&block)
end

.peersObject

rubocop:enable Metrics/AbcSize rubocop:enable Metrics/PerceivedComplexity



45
46
47
48
49
50
51
# File 'lib/net/knocker/peer.rb', line 45

def self.peers
  @peers ||= Dir['/proc/*/'].map do |path|
    try_peer(path).tap do |p|
      debug("peer found #{p.pid}") unless p.nil?
    end
  end.compact
end

.pidsObject



53
54
55
# File 'lib/net/knocker/peer.rb', line 53

def self.pids
  @pids ||= peers.map(&:pid)
end

.try_peer(path) ⇒ Object

rubocop:todo Metrics/PerceivedComplexity rubocop:todo Metrics/AbcSize



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/net/knocker/peer.rb', line 25

def self.try_peer(path) # rubocop:todo Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
  pid = File.basename(path).to_i
  return if pid.zero? || (pid.eql? Process.pid)

  peer_candidate = new(pid)
  return unless peer_candidate.exe.basename.eql? Pathname('/proc/self/exe').realpath.basename
  return unless var_names.all? { |e| peer_candidate.environ.key? e }
  return unless URI.parse(peer_candidate.environ.fetch('NET_KNOCKER_URL')).eql? url
  return unless peer_candidate.environ.fetch('NET_KNOCKER_SECRET').eql? env_secret

  peer_candidate
rescue Errno::EACCES
  nil
rescue StandardError => e
  debug "non-crical exception raised: #{e.class}: #{e.message}"
  nil
end

Instance Method Details

#environObject



17
18
19
20
21
# File 'lib/net/knocker/peer.rb', line 17

def environ
  @environ ||= environ_path.binread.split("\0").map do |line|
    line.split('=', 2)
  end.to_h
end