Class: ProxyDaemon::Daemon
- Inherits:
-
Object
- Object
- ProxyDaemon::Daemon
- Defined in:
- lib/proxy_daemon/daemon.rb
Instance Method Summary collapse
- #command(cmd, pipe, *params) ⇒ Object
-
#initialize(script, options) ⇒ Daemon
constructor
A new instance of Daemon.
- #listen(pipe, try = 0) ⇒ Object
- #start ⇒ Object
- #worker ⇒ Object
Constructor Details
#initialize(script, options) ⇒ Daemon
Returns a new instance of Daemon.
8 9 10 11 12 13 14 15 16 17 |
# File 'lib/proxy_daemon/daemon.rb', line 8 def initialize(script, ) @script = script @proxies = (([:proxies].map { |proxy| proxy.gsub /\s+/, ' ' }) || []).shuffle @urls = [:urls] || [] @workers = [:workers] || 10 @tries = [:tries] || 4 @threads = [] @semaphore = Mutex.new end |
Instance Method Details
#command(cmd, pipe, *params) ⇒ Object
19 20 21 22 |
# File 'lib/proxy_daemon/daemon.rb', line 19 def command(cmd, pipe, *params) Thread.current[:command] = cmd pipe.syswrite("#{cmd} #{params.join(' ')}\n") end |
#listen(pipe, try = 0) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/proxy_daemon/daemon.rb', line 24 def listen(pipe, try = 0) answer = (pipe.sysread(30) || '').strip if answer == 'proxy' raise "Broken url: #{Thread.current[:url]}" if try > @tries proxy = getProxy log "Choosing new proxy: #{(proxy || 'nil').yellow}", pipe command :proxy, pipe, proxy command :url, pipe, Thread.current[:url] listen pipe, try+1 elsif answer.empty? raise "Empty answer from worker process" elsif answer == 'timeout' || answer == 'error' raise "Process: '#{answer}'" elsif Thread.current[:command] == :url log "Process: #{Thread.current[:url].cyan}: '#{answer.green}'", pipe else log "Answer: #{answer}".green, pipe end end |
#start ⇒ Object
86 87 88 89 90 |
# File 'lib/proxy_daemon/daemon.rb', line 86 def start puts "[main] Starting " + "#{@workers}".yellow + " workers:" @workers.times { |i| @threads << Thread.new(&(->{worker})) } @threads.each { |t| t.join } end |
#worker ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/proxy_daemon/daemon.rb', line 46 def worker IO.popen("#{@script}", 'r+') { |p| proxy = getProxy log "Starting loop with new proxy: ".green + "#{(proxy || 'nil').yellow}", p command :proxy, p, proxy begin loop do sleep(0.1) url = getUrl if url.nil? finished "Links are finished! exitting...".green, p command :exit, p break else log 'Urls count: ' + "#{@urls.length}".green + ", #{url.green}" Thread.current[:url] = url command :url, p, url listen p end end log "Finishing loop".green, p rescue Exception => e @semaphore.synchronize { log "Exception in main: " + "#{e.message.red}, '#{Thread.current[:url]}'".red, p command :exit, p #puts e.backtrace } end } if @urls.length > 0 # @threads << Thread.new(&(->{worker})) # @threads.last.join worker end end |