Skip to content

Instantly share code, notes, and snippets.

@erukiti
Created February 4, 2013 14:18
Show Gist options
  • Save erukiti/4706943 to your computer and use it in GitHub Desktop.
Save erukiti/4706943 to your computer and use it in GitHub Desktop.
Fluentd Forwardを受け付けて、IRCに流すbotのサンプル
#! ruby
# coding: utf-8
#
# Fleuntd bot sample
CONF = {
server: "<IRC SERVER HOST>",
port: <IRC SERVER PORT>,
nick: "<NICK>",
user: "<USERNAME>",
real: "<REALNAME>",
channel: "<IRC CHANNEL>",
}
require 'net/irc'
class OutIRC < Net::IRC::Client
def initialize(*args)
super
@queue = args[2][:queue]
@channel = CONF[:channel]
@mutex = Mutex.new
@timer_thread = Thread.new do
while true
sleep(1)
on_timer
end
end
end
def on_rpl_welcome(m)
post JOIN, @channel
@counter = Time.now() - 60 * 60 * 4
end
def on_timer
while data = @queue.pop
post NOTICE, @channel, data.to_s
end
end
def post(command, *params)
@mutex.synchronize do
super
end
end
end
class Queue
def initialize
@mutex = Mutex.new
@buffer = []
end
def <<(data)
@mutex.synchronize do
@buffer << data
end
end
def pop
data = nil
@mutex.synchronize do
data = @buffer.shift
end
data
end
end
require 'msgpack'
require 'socket'
class InFluentdForward
def initialize(queue)
@port = 24224
@server = TCPServer.open(@port)
@usock = UDPSocket.new
@usock.bind('0.0.0.0', @port)
@queue = queue
end
def start
Thread.start do
while true
Thread.start(@server.accept) do |s|
begin
while s.gets
msg = MessagePack.unpack($_)
#p "msg.size: #{msg.size}"
tag = msg[0].to_s
if msg[1].class == String
MessagePack::Unpacker.new.feed_each(msg[1]) { |data|
@queue << "#{tag}:#{data[1].inspect}"
}
elsif msg[1].class == Array
msg[1].each do |time, data|
@queue << "#{tag}:#{data.inspect}"
end
else
@queue << "#{tag}:#{msg[1].inspect}:#{msg[2].inspect}"
end
end
s.close
rescue
p $!
end
end
end
end
Thread.start do
while true
msg, addr = @usock.recvfrom(1024)
@usock.send "\0", 0, addr[3], addr[1]
end
end
end
end
queue = Queue.new
in_forward = InFluentdForward.new(queue)
in_forward.start
OutIRC.new(CONF[:server], CONF[:port], {
:nick => CONF[:nick],
:user => CONF[:user],
:real => CONF[:real],
:queue => queue
}).start
#while true
# data = queue.pop
# puts data if data
#end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment