Class: Loghandler::Server

Inherits:
EM::Connection
  • Object
show all
Includes:
MongoMapper
Defined in:
lib/loghandler/server.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ws_channel) ⇒ Server

Returns a new instance of Server.



8
9
10
11
# File 'lib/loghandler/server.rb', line 8

def initialize(ws_channel)
  @ws_channel = ws_channel
  super
end

Class Method Details

.run(options) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/loghandler/server.rb', line 61

def self.run(options)
  MongoMapper.connection = Mongo::Connection.new()
  MongoMapper.database = "loghandler"

  EM.run do
    ws_channel = EventMachine::Channel.new
    Signal.trap("INT") do
      EM.stop
    end
    EventMachine.start_server options[:url], options[:port], Loghandler::Server, ws_channel
    
    EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 8080) do |ws|
        ws.onopen do
          ws_channel.subscribe do |msg|
            ws.send msg 
          end
        end
        # ws.onclose { puts "Connection closed" }
        # ws.onmessage { |msg|
        #   puts "Recieved message: #{msg}"
        #   ws.send "Pong: #{msg}"
        # }
    end
    
 end # EM
end

Instance Method Details

#apply_rules(log_detail) ⇒ Object



31
32
33
34
35
36
37
38
# File 'lib/loghandler/server.rb', line 31

def apply_rules(log_detail)
  detect_matching_rules(log_detail).each do |rule|
    rule.apply!
    # puts "logging: #{rule.log}" if !rule.loggable?
    @ws_channel.push(rule.log) if rule.loggable?
  end
  
end

#detect_matching_rules(log_detail) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/loghandler/server.rb', line 19

def detect_matching_rules(log_detail)
  matching_rules = []

  @rules.each do |rule_name|
    rule_class = Loghandler::Rules.const_get(rule_name)
    rule = rule_class.new(log_detail)
    matching_rules << rule if rule.match?
  end

  return matching_rules
end

#post_initObject



13
14
15
16
17
# File 'lib/loghandler/server.rb', line 13

def post_init
  @rules=Loghandler::Rules.constants.select {|c| Class === Loghandler::Rules.const_get(c)}
  @rules.delete(:AbstractRule)
  @tmp_line = []
end

#receive_data(rawdata) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/loghandler/server.rb', line 40

def receive_data(rawdata)
  rawdata.each_line do |data|
    if (!@tmp_line.empty?)
      data = [@tmp_line,data].join
    end
    begin
      # TODO : Risk of infinite loop + Memory Leak. Find a better test than an Error on parsing.
      # => What's happen if one json is invalid ? At this time, the process can't detect anything
      data=JSON.parse(data)
    rescue => e
      # ligne incomplete
      @tmp_line << data
      next
    end
    @tmp_line = []
    data = Hash[data.map{|(k,v)| [k.to_sym,v]}]
    data[:content].strip!
    apply_rules(data)
  end
end