repo
string
commit
string
message
string
diff
string
darxriggs/ip-world-map
ba807e4c7616ad2ae99694af3e599954d79b49c9
fix license id to match SPDX identifier
diff --git a/Rakefile b/Rakefile index 38fb936..1d629b3 100644 --- a/Rakefile +++ b/Rakefile @@ -1,47 +1,47 @@ # -*- coding: utf-8 -*- require 'rubygems' require 'rubygems/package_task' require 'rspec/core/rake_task' RSpec::Core::RakeTask.new do |t| t.pattern = 'spec/**/*.rb' t.rcov = false t.rcov_opts = %q[--exclude "spec"] t.verbose = true end spec = Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 1.8.7' s.summary = 'A tool to generate images/videos of user locations based on Apache log files.' s.name = 'ip-world-map' s.version = '1.0.0' - s.license = 'GPL-2' + s.license = 'GPL-2.0' s.executables = ['ip-world-map'] s.files = FileList['{lib,spec}/**/*'].to_a + ['Rakefile'] + ['resources/maps/earthmap-1920x960.tif'] s.has_rdoc = false s.description = s.summary s.homepage = 'http://github.com/darxriggs/ip-world-map' s.author = 'René Scheibe' s.email = 'rene.scheibe@gmail.com' s.requirements = ['ImageMagick (used by rmagick)', 'ffmpeg (only for animations)'] s.required_ruby_version = '>= 1.8.7' s.add_runtime_dependency('rmagick', '~> 2.13', '>= 2.13.1') s.add_runtime_dependency('typhoeus', '~> 0.2', '>= 0.2.1') s.add_development_dependency('rspec', '~> 2.6', '>= 2.6.0') end Gem::PackageTask.new(spec) do |pkg| pkg.need_tar = false end desc 'Install gem locally' task :install_gem => :package do `gem install pkg/*.gem --no-ri --no-rdoc` end task :default => :install_gem
darxriggs/ip-world-map
b754eac8ec647ee657d0f8038d07be487235cf5e
set minimum Ruby required version
diff --git a/Rakefile b/Rakefile index 0dda5d3..38fb936 100644 --- a/Rakefile +++ b/Rakefile @@ -1,46 +1,47 @@ # -*- coding: utf-8 -*- require 'rubygems' require 'rubygems/package_task' require 'rspec/core/rake_task' RSpec::Core::RakeTask.new do |t| t.pattern = 'spec/**/*.rb' t.rcov = false t.rcov_opts = %q[--exclude "spec"] t.verbose = true end spec = Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 1.8.7' s.summary = 'A tool to generate images/videos of user locations based on Apache log files.' s.name = 'ip-world-map' s.version = '1.0.0' s.license = 'GPL-2' s.executables = ['ip-world-map'] s.files = FileList['{lib,spec}/**/*'].to_a + ['Rakefile'] + ['resources/maps/earthmap-1920x960.tif'] s.has_rdoc = false s.description = s.summary s.homepage = 'http://github.com/darxriggs/ip-world-map' s.author = 'René Scheibe' s.email = 'rene.scheibe@gmail.com' s.requirements = ['ImageMagick (used by rmagick)', 'ffmpeg (only for animations)'] + s.required_ruby_version = '>= 1.8.7' s.add_runtime_dependency('rmagick', '~> 2.13', '>= 2.13.1') s.add_runtime_dependency('typhoeus', '~> 0.2', '>= 0.2.1') s.add_development_dependency('rspec', '~> 2.6', '>= 2.6.0') end Gem::PackageTask.new(spec) do |pkg| pkg.need_tar = false end desc 'Install gem locally' task :install_gem => :package do `gem install pkg/*.gem --no-ri --no-rdoc` end task :default => :install_gem
darxriggs/ip-world-map
eb475c9fa799adcdf0cbddab02f64db9473add46
add missing typhoeus dependency
diff --git a/Rakefile b/Rakefile index 239df13..0dda5d3 100644 --- a/Rakefile +++ b/Rakefile @@ -1,45 +1,46 @@ # -*- coding: utf-8 -*- require 'rubygems' require 'rubygems/package_task' require 'rspec/core/rake_task' RSpec::Core::RakeTask.new do |t| t.pattern = 'spec/**/*.rb' t.rcov = false t.rcov_opts = %q[--exclude "spec"] t.verbose = true end spec = Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 1.8.7' s.summary = 'A tool to generate images/videos of user locations based on Apache log files.' s.name = 'ip-world-map' s.version = '1.0.0' s.license = 'GPL-2' s.executables = ['ip-world-map'] s.files = FileList['{lib,spec}/**/*'].to_a + ['Rakefile'] + ['resources/maps/earthmap-1920x960.tif'] s.has_rdoc = false s.description = s.summary s.homepage = 'http://github.com/darxriggs/ip-world-map' s.author = 'René Scheibe' s.email = 'rene.scheibe@gmail.com' s.requirements = ['ImageMagick (used by rmagick)', 'ffmpeg (only for animations)'] s.add_runtime_dependency('rmagick', '~> 2.13', '>= 2.13.1') + s.add_runtime_dependency('typhoeus', '~> 0.2', '>= 0.2.1') s.add_development_dependency('rspec', '~> 2.6', '>= 2.6.0') end Gem::PackageTask.new(spec) do |pkg| pkg.need_tar = false end desc 'Install gem locally' task :install_gem => :package do `gem install pkg/*.gem --no-ri --no-rdoc` end task :default => :install_gem
darxriggs/ip-world-map
c4e70dbe3a290db6db89d14dee207943c6e0cfec
relax pessimistic dependency declarations
diff --git a/Rakefile b/Rakefile index a131a21..239df13 100644 --- a/Rakefile +++ b/Rakefile @@ -1,45 +1,45 @@ # -*- coding: utf-8 -*- require 'rubygems' require 'rubygems/package_task' require 'rspec/core/rake_task' RSpec::Core::RakeTask.new do |t| t.pattern = 'spec/**/*.rb' t.rcov = false t.rcov_opts = %q[--exclude "spec"] t.verbose = true end spec = Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 1.8.7' s.summary = 'A tool to generate images/videos of user locations based on Apache log files.' s.name = 'ip-world-map' s.version = '1.0.0' s.license = 'GPL-2' s.executables = ['ip-world-map'] s.files = FileList['{lib,spec}/**/*'].to_a + ['Rakefile'] + ['resources/maps/earthmap-1920x960.tif'] s.has_rdoc = false s.description = s.summary s.homepage = 'http://github.com/darxriggs/ip-world-map' s.author = 'René Scheibe' s.email = 'rene.scheibe@gmail.com' s.requirements = ['ImageMagick (used by rmagick)', 'ffmpeg (only for animations)'] - s.add_runtime_dependency('rmagick', '~> 2.13.1') - s.add_development_dependency('rspec', '~> 2.6.0') + s.add_runtime_dependency('rmagick', '~> 2.13', '>= 2.13.1') + s.add_development_dependency('rspec', '~> 2.6', '>= 2.6.0') end Gem::PackageTask.new(spec) do |pkg| pkg.need_tar = false end desc 'Install gem locally' task :install_gem => :package do `gem install pkg/*.gem --no-ri --no-rdoc` end task :default => :install_gem
darxriggs/ip-world-map
6344b5de929e3a34c8d41fe8f9143a292aadaa2d
no more sudo to install the gem
diff --git a/README.rdoc b/README.rdoc index fffb227..3588eb2 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,67 +1,67 @@ = IP World Map This tool can be used to visualize web access logfiles. It performs geo-location resolution on the IPs (using api.hostip.info) and can generate: * a fixed image * an animated image * a video == Installation Install [Gemcutter](http://gemcutter.org) then execute: - sudo gem install ip-world-map + gem install ip-world-map == Usage ip-world-map [options] logfile1 [logfile2] ... == Options --version Display the version -h, --help Display this help message -v, --verbose Verbose output --map-filename VALUE The image to use as background --resolution VALUE (eg.: 640x480) --fps VALUE Animation frames per second (eg.: 25) --fill-dot-color VALUE (eg.: red, 'rgb(255,0,0)', '#FF0000') --fill-dot-scale VALUE (eg.: 10.0) --fill-dot-opacity VALUE range 0.0-1.0 (eg.: 0.0, 0.5, 1.0) --fill-dot-lifetime VALUE (eg.: 15) --time-slot VALUE real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day) --output-format VALUE image format (e.g.: gif, jpg, png) or video format (avi, mpg, mp4) --[no-]animate generate an image or a video == Examples Generate PNG image. That's the default output. ip-world-map /var/log/apache2/access.log* Generate AVI video with 640x480 and 25fps (default settings). ip-world-map --animate --output-format avi /var/log/apache2/access.log* == Supported platforms Tested with Ruby 1.8.7, 1.9.1 under *nix == Author René Scheibe == License Copyright (C) 2010-2011 René Scheibe <rene.scheibe@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. diff --git a/Rakefile b/Rakefile index 9d1dc93..a131a21 100644 --- a/Rakefile +++ b/Rakefile @@ -1,45 +1,45 @@ # -*- coding: utf-8 -*- require 'rubygems' require 'rubygems/package_task' require 'rspec/core/rake_task' RSpec::Core::RakeTask.new do |t| t.pattern = 'spec/**/*.rb' t.rcov = false t.rcov_opts = %q[--exclude "spec"] t.verbose = true end spec = Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 1.8.7' s.summary = 'A tool to generate images/videos of user locations based on Apache log files.' s.name = 'ip-world-map' s.version = '1.0.0' s.license = 'GPL-2' s.executables = ['ip-world-map'] s.files = FileList['{lib,spec}/**/*'].to_a + ['Rakefile'] + ['resources/maps/earthmap-1920x960.tif'] s.has_rdoc = false s.description = s.summary s.homepage = 'http://github.com/darxriggs/ip-world-map' s.author = 'René Scheibe' s.email = 'rene.scheibe@gmail.com' s.requirements = ['ImageMagick (used by rmagick)', 'ffmpeg (only for animations)'] s.add_runtime_dependency('rmagick', '~> 2.13.1') s.add_development_dependency('rspec', '~> 2.6.0') end Gem::PackageTask.new(spec) do |pkg| pkg.need_tar = false end desc 'Install gem locally' task :install_gem => :package do - `sudo gem install pkg/*.gem --no-ri --no-rdoc` + `gem install pkg/*.gem --no-ri --no-rdoc` end task :default => :install_gem
darxriggs/ip-world-map
53f4689fbb9f126eca4aef8def2bda1880fa6964
fix to make it work with Ruby 1.9
diff --git a/bin/ip-world-map b/bin/ip-world-map index f76da4c..5616bee 100755 --- a/bin/ip-world-map +++ b/bin/ip-world-map @@ -1,183 +1,183 @@ #!/usr/bin/env ruby require 'rubygems' require 'optparse' require 'ostruct' require 'date' require 'ip-world-map' require 'RMagick' class App VERSION = '0.0.1' attr_reader :options def initialize arguments, stdin @arguments = arguments @stdin = stdin set_defaults end def run if parsed_arguments? && arguments_valid? output_options if @options.verbose process_command else output_help exit 1 end end protected def set_defaults @options = OpenStruct.new({ :verbose => false, :quiet => false, :map_filename => File.join(File.dirname(__FILE__), '..' , 'resources', 'maps', 'earthmap-1920x960.tif'), :map_width => 800, :map_height => 400, :frames_per_second => 25, :fill_dot_color => 'red', :fill_dot_scale => 10, :fill_dot_opacity => 1.0, :fill_dot_lifetime => 15, :time_format => nil, :group_seconds => 24 * 1 * 60 * 60, :output_format => 'png', :animate => false }) end def parsed_arguments? @opts = opts = OptionParser.new opts.banner = 'Usage: ip-world-map [options] log_file1 [logfile2] ...' opts.on('--version', 'Display the version') do output_version exit 0 end opts.on('-h', '--help', 'Display this help message') do output_help exit 0 end opts.on('-v', '--verbose', 'Verbose output') do @options.verbose = true end opts.on('--map-filename VALUE', 'The image to use as background') do |filename| raise 'invalid map file' unless File.readable? filename @options.map_filename = filename end opts.on('--resolution VALUE', '(eg.: 640x480)') do |resolution| raise 'invalid resolution format' unless resolution =~ /^[0-9]+x[0-9]+$/ width, height = resolution.split('x').collect{|v| v.to_i} @options.map_width = width @options.map_height = height end opts.on('--fps VALUE', 'Animation frames per second (eg.: 25)') do |fps| raise 'invalid fps format' unless fps =~ /^[1-9][0-9]*$/ @options.frames_per_second = fps.to_i end opts.on('--fill-dot-color VALUE', "(eg.: red, 'rgb(255,0,0)', '#FF0000')") do |color| Magick::Pixel.from_color color rescue raise 'invalid color (see help for examples)' @options.fill_dot_color = color end opts.on('--fill-dot-scale VALUE', '(eg.: 10.0)') do |scale| raise 'invalid dot scale' unless scale =~ /^[1-9][0-9]*([.][0-9]*)?$/ @options.fill_dot_scale = scale.to_f end opts.on('--fill-dot-opacity VALUE', 'range 0.0-1.0 (eg.: 0.0, 0.5, 1.0)') do |opacity| raise 'invalid dot opacity' unless opacity =~ /^(0([.][0-9]*)?|1([.]0*)?)$/ @options.fill_dot_opacity = opacity.to_f end opts.on('--fill-dot-lifetime VALUE', '(eg.: 15)') do |lifetime| raise 'invalid dot lifetime' unless lifetime =~ /^[1-9][0-9]*$/ @options.fill_dot_lifetime = lifetime.to_i end opts.on('--time-slot VALUE', 'real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day)') do |slot| raise 'invalid time slot' unless slot =~ /^[1-9][0-9]*(sec|min|hour|day)s?$/ value = slot.scan(/[0-9]+/)[0].to_i unit = slot.scan(/[a-z]+[^s]/)[0] unit2secs = {'sec' => 1, 'min' => 60, 'hour' => 60*60, 'day' => 24*60*60} @options.group_seconds = value * unit2secs[unit] end # TODO # opts.on('--time-format', 'gets auto-detected if not specified') { |v| @options.time_format = v } opts.on('--output-format VALUE', 'image format (e.g.: gif, jpg, png) or video format (avi, mpg, mp4)') do |format| video_formats = %w[avi mpg mp4] is_supported = Magick.formats.any?{ |supported_format, properties| supported_format.upcase == format.upcase && properties.include?('w') } is_supported |= video_formats.any?{ |supported_format| supported_format.upcase == format.upcase } raise 'invalid output format' unless is_supported @options.output_format = format end opts.on('--[no-]animate', 'generate an image or a video') do |animate| @options.animate = animate end begin opts.parse!(@arguments) @log_files = Dir.glob(@arguments) raise 'no log files given' if @log_files.empty? raise 'invalid log file given' unless @log_files.all?{|file| File.readable? file} process_options rescue - puts 'Error: ' + $! + puts 'Error: ' + $!.to_s return false end true end # Performs post-parse processing on options def process_options $visualization_config = @options end def output_options puts 'Options:' @options.marshal_dump.sort{|a,b| a[0].to_s <=> b[0].to_s}.each do |name, val| puts " #{name} = #{val}" end end # True if required arguments were provided def arguments_valid? video_formats = %w[avi mpg mp4] is_video_format = video_formats.any?{ |video_format| video_format == @options.output_format.downcase } return false if !@options.animate && is_video_format return false if @options.animate && !is_video_format true end def output_help puts @opts.help end def output_version puts "#{File.basename(__FILE__)} version #{VERSION}" end def process_command ApacheLogVisualizer.new(@log_files).visualize end end # Create and run the application app = App.new(ARGV, STDIN) app.run
darxriggs/ip-world-map
6a220b496ae097f9a2a302f1c6c188433534577f
upgraded to v1.0.0 for official release
diff --git a/Rakefile b/Rakefile index a2e3475..9d1dc93 100644 --- a/Rakefile +++ b/Rakefile @@ -1,45 +1,45 @@ # -*- coding: utf-8 -*- require 'rubygems' require 'rubygems/package_task' require 'rspec/core/rake_task' RSpec::Core::RakeTask.new do |t| t.pattern = 'spec/**/*.rb' t.rcov = false t.rcov_opts = %q[--exclude "spec"] t.verbose = true end spec = Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 1.8.7' s.summary = 'A tool to generate images/videos of user locations based on Apache log files.' s.name = 'ip-world-map' - s.version = '0.0.1' + s.version = '1.0.0' s.license = 'GPL-2' s.executables = ['ip-world-map'] s.files = FileList['{lib,spec}/**/*'].to_a + ['Rakefile'] + ['resources/maps/earthmap-1920x960.tif'] s.has_rdoc = false s.description = s.summary s.homepage = 'http://github.com/darxriggs/ip-world-map' s.author = 'René Scheibe' s.email = 'rene.scheibe@gmail.com' s.requirements = ['ImageMagick (used by rmagick)', 'ffmpeg (only for animations)'] s.add_runtime_dependency('rmagick', '~> 2.13.1') s.add_development_dependency('rspec', '~> 2.6.0') end Gem::PackageTask.new(spec) do |pkg| pkg.need_tar = false end desc 'Install gem locally' task :install_gem => :package do `sudo gem install pkg/*.gem --no-ri --no-rdoc` end task :default => :install_gem
darxriggs/ip-world-map
f3e009f653288a8496b46ec5d268b777d20f8230
fixed issue with class method
diff --git a/lib/ip-world-map/apache_log_visualizer.rb b/lib/ip-world-map/apache_log_visualizer.rb index 50264db..067b3cb 100644 --- a/lib/ip-world-map/apache_log_visualizer.rb +++ b/lib/ip-world-map/apache_log_visualizer.rb @@ -1,75 +1,75 @@ require 'RMagick' class ApacheLogVisualizer def initialize log_files @log_files = log_files end def self.detect_time_format times some_samples = times.sort[0..99] smallest_period = some_samples.each_cons(2).collect{ |time1, time2| (time1 - time2).abs }.min || 1 return '%b %d %Y %H:%M' if smallest_period < 3600 # scale: minutes return '%b %d %Y %H:00' if smallest_period < 86400 # scale: hours return '%b %d %Y' # scale: days end def generate_image analyzer = ApacheLogAnalyzer.new(@log_files) details = analyzer.analyze positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } visualization = Visualization.new image = visualization.draw_positions(positions) save_image image end def generate_animation analyzer = ApacheLogAnalyzer.new(@log_files) details = analyzer.analyze grouped_details = analyzer.group_by_time(details, $visualization_config.group_seconds) animation = Magick::ImageList.new visualization = Visualization.new - time_format = $visualization_config.time_format || detect_time_format(grouped_details.keys) + time_format = $visualization_config.time_format || ApacheLogVisualizer.detect_time_format(grouped_details.keys) frame_number = 0 puts "\nGenerating frames:" if $visualization_config.verbose grouped_details.sort.each do |time, details| frame_number += 1 visualization.new_frame positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } p [time, details.size, positions.size] if $visualization_config.verbose image = visualization.draw_positions(positions) InformationDrawer.new.draw_info(image, visualization, time.strftime(time_format)) save_image image, frame_number end render_frames_as_video end def save_image image, frame_number = 0 if $visualization_config.animate image.write "animation.#{'%09d' % frame_number}.bmp" else image.write "snapshot.#{$visualization_config.output_format}" end end def render_frames_as_video puts "\nGenerating video:" if $visualization_config.verbose output = `ffmpeg -r #{$visualization_config.frames_per_second} -qscale 1 -y -i animation.%09d.bmp animation.#{$visualization_config.output_format} 2>&1` puts output if $visualization_config.verbose raise 'could not create the animation' unless $?.exitstatus == 0 end def visualize if $visualization_config.animate generate_animation else generate_image end end end
darxriggs/ip-world-map
6b892f331103b85ed23218f81cf44bb043cfed31
removed TODO (already implemented)
diff --git a/README.rdoc b/README.rdoc index d155ba3..29b86d1 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,68 +1,64 @@ = IP World Map This tool can be used to visualize web access logfiles. It performs geo-location resolution on the IPs (using api.hostip.info) and can generate: * a fixed image * an animated image * a video == Installation Install [Gemcutter](http://gemcutter.org) then execute: sudo gem install ip-world-map == Supported platforms Tested with Ruby 1.8.7, 1.9.1 under *nix == Examples The script generates an animated gif with 640x480 and 25fps (default settings). ip-world-map /var/log/apache2/access.log* == Usage ip-world-map [options] logfile1 [logfile2] ... == Options --version Display the version -h, --help Display this help message -v, --verbose Verbose output --map-filename VALUE The image to use as background --resolution VALUE (eg.: 640x480) --fps VALUE Animation frames per second (eg.: 25) --fill-dot-color VALUE (eg.: red, 'rgb(255,0,0)', '#FF0000') --fill-dot-scale VALUE (eg.: 10.0) --fill-dot-opacity VALUE range 0.0-1.0 (eg.: 0.0, 0.5, 1.0) --fill-dot-lifetime VALUE (eg.: 15) --time-slot VALUE real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day) --output-format VALUE image format (e.g.: gif, jpg, png) or video format (avi, mpg, mp4) --[no-]animate generate an image or a video -== TODO - -* Cache/parallelize IP geo-location lookups. ATTENTION: For many IPs generating an animation can take quite long at the moment due to the used webservice. - == Author René Scheibe == License Copyright (C) 2010-2011 René Scheibe <rene.scheibe@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
darxriggs/ip-world-map
7706eab3d5ce190eacea5ec2d699fd6990be964a
changed default image format from 'jpg' to 'png' due to compression artefacts
diff --git a/bin/ip-world-map b/bin/ip-world-map index 147a92c..26d6705 100755 --- a/bin/ip-world-map +++ b/bin/ip-world-map @@ -1,185 +1,185 @@ #!/usr/bin/env ruby require 'rubygems' require 'optparse' require 'ostruct' require 'date' require 'ip-world-map' require 'RMagick' class App VERSION = '0.0.1' attr_reader :options def initialize arguments, stdin @arguments = arguments @stdin = stdin set_defaults end def run if parsed_arguments? && arguments_valid? puts "Start at #{DateTime.now}\n\n" if @options.verbose output_options if @options.verbose process_command puts "\nFinished at #{DateTime.now}" if @options.verbose else output_help exit 1 end end protected def set_defaults @options = OpenStruct.new({ :verbose => false, :quiet => false, :map_filename => File.join(File.dirname(__FILE__), '..' , 'resources', 'maps', 'earthmap-1920x960.tif'), :map_width => 800, :map_height => 400, :frames_per_second => 25, :fill_dot_color => 'red', :fill_dot_scale => 10, :fill_dot_opacity => 1.0, :fill_dot_lifetime => 15, :time_format => nil, :group_seconds => 24 * 1 * 60 * 60, - :output_format => 'jpg', + :output_format => 'png', :animate => false }) end def parsed_arguments? @opts = opts = OptionParser.new opts.banner = 'Usage: ip-world-map [options] log_file1 [logfile2] ...' opts.on('--version', 'Display the version') do output_version exit 0 end opts.on('-h', '--help', 'Display this help message') do output_help exit 0 end opts.on('-v', '--verbose', 'Verbose output') do @options.verbose = true end opts.on('--map-filename VALUE', 'The image to use as background') do |filename| raise 'invalid map file' unless File.readable? filename @options.map_filename = filename end opts.on('--resolution VALUE', '(eg.: 640x480)') do |resolution| raise 'invalid resolution format' unless resolution =~ /^[0-9]+x[0-9]+$/ width, height = resolution.split('x').collect{|v| v.to_i} @options.map_width = width @options.map_height = height end opts.on('--fps VALUE', 'Animation frames per second (eg.: 25)') do |fps| raise 'invalid fps format' unless fps =~ /^[1-9][0-9]*$/ @options.frames_per_second = fps.to_i end opts.on('--fill-dot-color VALUE', "(eg.: red, 'rgb(255,0,0)', '#FF0000')") do |color| Magick::Pixel.from_color color rescue raise 'invalid color (see help for examples)' @options.fill_dot_color = color end opts.on('--fill-dot-scale VALUE', '(eg.: 10.0)') do |scale| raise 'invalid dot scale' unless scale =~ /^[1-9][0-9]*([.][0-9]*)?$/ @options.fill_dot_scale = scale.to_f end opts.on('--fill-dot-opacity VALUE', 'range 0.0-1.0 (eg.: 0.0, 0.5, 1.0)') do |opacity| raise 'invalid dot opacity' unless opacity =~ /^(0([.][0-9]*)?|1([.]0*)?)$/ @options.fill_dot_opacity = opacity.to_f end opts.on('--fill-dot-lifetime VALUE', '(eg.: 15)') do |lifetime| raise 'invalid dot lifetime' unless lifetime =~ /^[1-9][0-9]*$/ @options.fill_dot_lifetime = lifetime.to_i end opts.on('--time-slot VALUE', 'real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day)') do |slot| raise 'invalid time slot' unless slot =~ /^[1-9][0-9]*(sec|min|hour|day)s?$/ value = slot.scan(/[0-9]+/)[0].to_i unit = slot.scan(/[a-z]+[^s]/)[0] unit2secs = {'sec' => 1, 'min' => 60, 'hour' => 60*60, 'day' => 24*60*60} @options.group_seconds = value * unit2secs[unit] end # TODO # opts.on('--time-format', 'gets auto-detected if not specified') { |v| @options.time_format = v } opts.on('--output-format VALUE', 'image format (e.g.: gif, jpg, png) or video format (avi, mpg, mp4)') do |format| video_formats = %w[avi mpg mp4] is_supported = Magick.formats.any?{ |supported_format, properties| supported_format.upcase == format.upcase && properties.include?('w') } is_supported |= video_formats.any?{ |supported_format| supported_format.upcase == format.upcase } raise 'invalid output format' unless is_supported @options.output_format = format end opts.on('--[no-]animate', 'generate an image or a video') do |animate| @options.animate = animate end begin opts.parse!(@arguments) @log_files = Dir.glob(@arguments) raise 'no log files given' if @log_files.empty? raise 'invalid log file given' unless @log_files.all?{|file| File.readable? file} process_options rescue puts 'Error: ' + $! return false end true end # Performs post-parse processing on options def process_options $visualization_config = @options end def output_options puts 'Options:' @options.marshal_dump.sort{|a,b| a[0].to_s <=> b[0].to_s}.each do |name, val| puts " #{name} = #{val}" end end # True if required arguments were provided def arguments_valid? video_formats = %w[avi mpg mp4] is_video_format = video_formats.any?{ |video_format| video_format == @options.output_format.downcase } return false if !@options.animate && is_video_format return false if @options.animate && !is_video_format true end def output_help puts @opts.help end def output_version puts "#{File.basename(__FILE__)} version #{VERSION}" end def process_command visualize @log_files end end # Create and run the application app = App.new(ARGV, STDIN) app.run
darxriggs/ip-world-map
5fa4941cbef706082285b3c1f6f5ada60766eb76
cleanup
diff --git a/bin/ip-world-map b/bin/ip-world-map index 4eebb57..147a92c 100755 --- a/bin/ip-world-map +++ b/bin/ip-world-map @@ -1,198 +1,185 @@ #!/usr/bin/env ruby require 'rubygems' require 'optparse' require 'ostruct' require 'date' require 'ip-world-map' +require 'RMagick' class App VERSION = '0.0.1' attr_reader :options def initialize arguments, stdin @arguments = arguments @stdin = stdin set_defaults end def run if parsed_arguments? && arguments_valid? puts "Start at #{DateTime.now}\n\n" if @options.verbose output_options if @options.verbose - process_arguments process_command puts "\nFinished at #{DateTime.now}" if @options.verbose else output_help exit 1 end end protected def set_defaults @options = OpenStruct.new({ :verbose => false, :quiet => false, :map_filename => File.join(File.dirname(__FILE__), '..' , 'resources', 'maps', 'earthmap-1920x960.tif'), :map_width => 800, :map_height => 400, :frames_per_second => 25, :fill_dot_color => 'red', :fill_dot_scale => 10, :fill_dot_opacity => 1.0, :fill_dot_lifetime => 15, :time_format => nil, :group_seconds => 24 * 1 * 60 * 60, - :output_format => 'gif', - :animate => true + :output_format => 'jpg', + :animate => false }) end def parsed_arguments? @opts = opts = OptionParser.new opts.banner = 'Usage: ip-world-map [options] log_file1 [logfile2] ...' opts.on('--version', 'Display the version') do output_version exit 0 end opts.on('-h', '--help', 'Display this help message') do output_help exit 0 end opts.on('-v', '--verbose', 'Verbose output') do @options.verbose = true end opts.on('--map-filename VALUE', 'The image to use as background') do |filename| raise 'invalid map file' unless File.readable? filename @options.map_filename = filename end opts.on('--resolution VALUE', '(eg.: 640x480)') do |resolution| raise 'invalid resolution format' unless resolution =~ /^[0-9]+x[0-9]+$/ width, height = resolution.split('x').collect{|v| v.to_i} @options.map_width = width @options.map_height = height end opts.on('--fps VALUE', 'Animation frames per second (eg.: 25)') do |fps| raise 'invalid fps format' unless fps =~ /^[1-9][0-9]*$/ @options.frames_per_second = fps.to_i end opts.on('--fill-dot-color VALUE', "(eg.: red, 'rgb(255,0,0)', '#FF0000')") do |color| Magick::Pixel.from_color color rescue raise 'invalid color (see help for examples)' @options.fill_dot_color = color end opts.on('--fill-dot-scale VALUE', '(eg.: 10.0)') do |scale| raise 'invalid dot scale' unless scale =~ /^[1-9][0-9]*([.][0-9]*)?$/ @options.fill_dot_scale = scale.to_f end opts.on('--fill-dot-opacity VALUE', 'range 0.0-1.0 (eg.: 0.0, 0.5, 1.0)') do |opacity| raise 'invalid dot opacity' unless opacity =~ /^(0([.][0-9]*)?|1([.]0*)?)$/ @options.fill_dot_opacity = opacity.to_f end opts.on('--fill-dot-lifetime VALUE', '(eg.: 15)') do |lifetime| raise 'invalid dot lifetime' unless lifetime =~ /^[1-9][0-9]*$/ @options.fill_dot_lifetime = lifetime.to_i end opts.on('--time-slot VALUE', 'real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day)') do |slot| raise 'invalid time slot' unless slot =~ /^[1-9][0-9]*(sec|min|hour|day)s?$/ value = slot.scan(/[0-9]+/)[0].to_i unit = slot.scan(/[a-z]+[^s]/)[0] unit2secs = {'sec' => 1, 'min' => 60, 'hour' => 60*60, 'day' => 24*60*60} @options.group_seconds = value * unit2secs[unit] end # TODO # opts.on('--time-format', 'gets auto-detected if not specified') { |v| @options.time_format = v } - opts.on('--output-format VALUE', 'one out of many image formats (eg.: png, jpg, gif) or video formats: avi, mpg, mp4') do |format| - # accepted_formats = %w[png gif jpg tif bmp avi mpg mp4] - # raise 'invalid output format' unless accepted_formats.include? format + opts.on('--output-format VALUE', 'image format (e.g.: gif, jpg, png) or video format (avi, mpg, mp4)') do |format| video_formats = %w[avi mpg mp4] is_supported = Magick.formats.any?{ |supported_format, properties| supported_format.upcase == format.upcase && properties.include?('w') } is_supported |= video_formats.any?{ |supported_format| supported_format.upcase == format.upcase } raise 'invalid output format' unless is_supported @options.output_format = format end opts.on('--[no-]animate', 'generate an image or a video') do |animate| @options.animate = animate end begin opts.parse!(@arguments) @log_files = Dir.glob(@arguments) raise 'no log files given' if @log_files.empty? raise 'invalid log file given' unless @log_files.all?{|file| File.readable? file} process_options rescue puts 'Error: ' + $! return false end true end # Performs post-parse processing on options def process_options $visualization_config = @options end def output_options puts 'Options:' @options.marshal_dump.sort{|a,b| a[0].to_s <=> b[0].to_s}.each do |name, val| puts " #{name} = #{val}" end end # True if required arguments were provided def arguments_valid? video_formats = %w[avi mpg mp4] is_video_format = video_formats.any?{ |video_format| video_format == @options.output_format.downcase } - return false if !@options.animate && is_video_format - return false if @options.animate && !is_video_format + return false if !@options.animate && is_video_format + return false if @options.animate && !is_video_format true end - def process_arguments - # TODO - place in local vars, etc - end - def output_help puts @opts.help end def output_version puts "#{File.basename(__FILE__)} version #{VERSION}" end def process_command - # TODO - do whatever this app does - #process_standard_input # [Optional] visualize @log_files end - - def process_standard_input - input = @stdin.read - # TODO - process input - end end # Create and run the application app = App.new(ARGV, STDIN) app.run diff --git a/lib/ip-world-map.rb b/lib/ip-world-map.rb index 31c11c7..e680bb8 100644 --- a/lib/ip-world-map.rb +++ b/lib/ip-world-map.rb @@ -1,16 +1,14 @@ require 'rubygems' -require 'RMagick' - require 'ip-world-map/ip_lookup_service' require 'ip-world-map/log_analyzer' require 'ip-world-map/information_drawer' require 'ip-world-map/apache_log_analyzer' require 'ip-world-map/apache_log_visualizer' require 'ip-world-map/decay' require 'ip-world-map/file_utils' require 'ip-world-map/point_in_time' require 'ip-world-map/visualization' require 'ip-world-map/logfile_mock' diff --git a/lib/ip-world-map/apache_log_visualizer.rb b/lib/ip-world-map/apache_log_visualizer.rb index 3d36b20..39ee4ae 100644 --- a/lib/ip-world-map/apache_log_visualizer.rb +++ b/lib/ip-world-map/apache_log_visualizer.rb @@ -1,68 +1,66 @@ -#coordinates_home = [11.6220338, 48.1276458] # Munich -#coordinates_home = [13.4114943, 52.5234802] # Berlin -#coordinates_home = [12.3387844, 45.4343363] # Venezia +require 'RMagick' def detect_time_format times some_samples = times.sort[0..99] smallest_period = some_samples.each_cons(2).collect{ |time1, time2| (time1 - time2).abs }.min || 1 return '%b %d %Y %H:%M' if smallest_period < 3600 # scale: minutes return '%b %d %Y %H:00' if smallest_period < 86400 # scale: hours return '%b %d %Y' # scale: days end def access_image log_files analyzer = ApacheLogAnalyzer.new(log_files) details = analyzer.analyze positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } visualization = Visualization.new image = visualization.draw_positions(positions) save_image image end def access_animation log_files analyzer = ApacheLogAnalyzer.new(log_files) details = analyzer.analyze grouped_details = analyzer.group_by_time(details, $visualization_config.group_seconds) animation = Magick::ImageList.new visualization = Visualization.new time_format = $visualization_config.time_format || detect_time_format(grouped_details.keys) frame_number = 0 grouped_details.sort.each do |time, details| frame_number += 1 visualization.new_frame positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } p [time, details.size, positions.size] image = visualization.draw_positions(positions) InformationDrawer.new.draw_info(image, visualization, time.strftime(time_format)) save_image image, frame_number end create_animation end def save_image image, frame_number = 0 if $visualization_config.animate image.write "animation.#{'%09d' % frame_number}.bmp" else image.write "snapshot.#{$visualization_config.output_format}" end end def create_animation success = system "ffmpeg -r #{$visualization_config.frames_per_second} -qscale 1 -y -i animation.%09d.bmp animation.#{$visualization_config.output_format}" raise 'could not create the animation' unless success end def visualize log_files if $visualization_config.animate access_animation(log_files) else access_image(log_files) end end diff --git a/lib/ip-world-map/information_drawer.rb b/lib/ip-world-map/information_drawer.rb index 2391d51..f815e93 100644 --- a/lib/ip-world-map/information_drawer.rb +++ b/lib/ip-world-map/information_drawer.rb @@ -1,32 +1,34 @@ +require 'RMagick' + # Draws the timestamp. class InformationDrawer def initialize @draw = Magick::Draw.new end def draw_info image, visualization, info size = { :width => visualization.map_size[:width], :height => visualization.map_size[:height] } draw_background(size) draw_message(size, info) @draw.draw(image) end protected def draw_background size width, height = size[:width], size[:height] @draw.fill('grey') @draw.fill_opacity('50%') @draw.rectangle(0.2 * width, 0.9 * height, 0.8 * width, 0.9 * height + 30) end def draw_message size, info @draw.fill('black') @draw.fill_opacity('100%') @draw.text_align(Magick::CenterAlign) @draw.pointsize(20) @draw.text(0.5 * size[:width], 0.9 * size[:height] + 20, info) end end diff --git a/lib/ip-world-map/visualization.rb b/lib/ip-world-map/visualization.rb index eee54b0..542cf2b 100644 --- a/lib/ip-world-map/visualization.rb +++ b/lib/ip-world-map/visualization.rb @@ -1,84 +1,83 @@ -require 'rubygems' require 'RMagick' class Visualization attr_accessor :position_quantization_in_degrees, :circle_radius def initialize @map_filename = $visualization_config.map_filename @raw_image = Magick::ImageList.new(@map_filename).first if $visualization_config.map_width || $visualization_config.map_height width = $visualization_config.map_width || @raw_image.columns height = $visualization_config.map_height || @raw_image.rows @raw_image.resize! width, height end new_frame @position_quantization_in_degrees = 10.0 @opacity_visibility_threshold = 0.1 @circle_radius = (map_size[:width] ** 1.25) / (map_size[:width] * $visualization_config.fill_dot_scale).to_f @points = [] end def map_size @map_size ||= { :width => @frame.columns, :height => @frame.rows } end def scale @scale ||= { :x => 360.0 / map_size[:width], :y => 180.0 / map_size[:height] } end def x_y_from_longitude_latitude longitude, latitude [ (180 + longitude) / scale[:x], (90 - latitude) / scale[:y] ] end def circle_parameters center_x, center_y [ center_x, center_y, center_x + circle_radius, center_y ] end def quantize_position position return position if @position_quantization_in_degrees == 0 position.collect{ |element| element - element.remainder(@position_quantization_in_degrees) } end def quantize_positions positions positions.collect{ |position| quantize_position(position) } end def select_visible_points points points.select{ |point| point.opacity >= @opacity_visibility_threshold } end def draw_positions positions_lon_lat @draw.fill($visualization_config.fill_dot_color) new_points = positions_lon_lat.collect do |longitude, latitude| x, y = x_y_from_longitude_latitude(longitude, latitude) PointInTime.new(x, y, $visualization_config.fill_dot_opacity, $visualization_config.fill_dot_lifetime) end @points = @points.concat(new_points) @points = select_visible_points(@points) # positions = quantize_positions(@positions) points = @points points.each do |point| @draw.fill_opacity(point.opacity) @draw.circle(*circle_parameters(point.x, point.y)) point.age end @draw.draw(@frame) @frame end def display @frame.display end def new_frame @draw = Magick::Draw.new @frame = @raw_image.clone end end
darxriggs/ip-world-map
ff90c6024ab031132d52236acfc26a9f8227cd19
moved methods into ApacheLogAnalyzer
diff --git a/bin/ip-world-map b/bin/ip-world-map index 00e33be..6156dc7 100755 --- a/bin/ip-world-map +++ b/bin/ip-world-map @@ -1,196 +1,196 @@ #!/usr/bin/env ruby require 'rubygems' require 'optparse' require 'ostruct' require 'date' require 'ip-world-map' class App VERSION = '0.0.1' attr_reader :options def initialize arguments, stdin @arguments = arguments @stdin = stdin set_defaults end def run if parsed_arguments? && arguments_valid? output_options if @options.verbose process_arguments process_command else output_help exit 1 end end protected def set_defaults @options = OpenStruct.new({ :verbose => false, :quiet => false, :map_filename => File.join(File.dirname(__FILE__), '..' , 'resources', 'maps', 'earthmap-1920x960.tif'), :map_width => 800, :map_height => 400, :frames_per_second => 25, :fill_dot_color => 'red', :fill_dot_scale => 10, :fill_dot_opacity => 1.0, :fill_dot_lifetime => 15, :time_format => nil, :group_seconds => 24 * 1 * 60 * 60, :output_format => 'mpg', :animate => true }) end def parsed_arguments? @opts = opts = OptionParser.new opts.banner = 'Usage: ip-world-map [options] log_file1 [logfile2] ...' opts.on('--version', 'Display the version') do output_version exit 0 end opts.on('-h', '--help', 'Display this help message') do output_help exit 0 end opts.on('-v', '--verbose', 'Verbose output') do @options.verbose = true end opts.on('--map-filename VALUE', 'The image to use as background') do |filename| raise 'invalid map file' unless File.readable? filename @options.map_filename = filename end opts.on('--resolution VALUE', '(eg.: 640x480)') do |resolution| raise 'invalid resolution format' unless resolution =~ /^[0-9]+x[0-9]+$/ width, height = resolution.split('x').collect{|v| v.to_i} @options.map_width = width @options.map_height = height end opts.on('--fps VALUE', 'Animation frames per second (eg.: 25)') do |fps| raise 'invalid fps format' unless fps =~ /^[1-9][0-9]*$/ @options.frames_per_second = fps.to_i end opts.on('--fill-dot-color VALUE', "(eg.: red, 'rgb(255,0,0)', '#FF0000')") do |color| Magick::Pixel.from_color color rescue raise 'invalid color (see help for examples)' @options.fill_dot_color = color end opts.on('--fill-dot-scale VALUE', '(eg.: 10.0)') do |scale| raise 'invalid dot scale' unless scale =~ /^[1-9][0-9]*([.][0-9]*)?$/ @options.fill_dot_scale = scale.to_f end opts.on('--fill-dot-opacity VALUE', 'range 0.0-1.0 (eg.: 0.0, 0.5, 1.0)') do |opacity| raise 'invalid dot opacity' unless opacity =~ /^(0([.][0-9]*)?|1([.]0*)?)$/ @options.fill_dot_opacity = opacity.to_f end opts.on('--fill-dot-lifetime VALUE', '(eg.: 15)') do |lifetime| raise 'invalid dot lifetime' unless lifetime =~ /^[1-9][0-9]*$/ @options.fill_dot_lifetime = lifetime.to_i end opts.on('--time-slot VALUE', 'real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day)') do |slot| raise 'invalid time slot' unless slot =~ /^[1-9][0-9]*(sec|min|hour|day)s?$/ value = slot.scan(/[0-9]+/)[0].to_i unit = slot.scan(/[a-z]+[^s]/)[0] unit2secs = {'sec' => 1, 'min' => 60, 'hour' => 60*60, 'day' => 24*60*60} @options.group_seconds = value * unit2secs[unit] end # TODO # opts.on('--time-format', 'gets auto-detected if not specified') { |v| @options.time_format = v } opts.on('--output-format VALUE', 'one out of many image formats (eg.: png, jpg, gif) or video formats: avi, mpg, mp4') do |format| # accepted_formats = %w[png gif jpg tif bmp avi mpg mp4] # raise 'invalid output format' unless accepted_formats.include? format video_formats = %w[avi mpg mp4] is_supported = Magick.formats.any?{ |supported_format, properties| supported_format.upcase == format.upcase && properties.include?('w') } is_supported |= video_formats.any?{ |supported_format| supported_format.upcase == format.upcase } raise 'invalid output format' unless is_supported @options.output_format = format end opts.on('--[no-]animate', 'generate an image or a video') do |animate| @options.animate = animate end begin opts.parse!(@arguments) @log_files = Dir.glob(@arguments) raise 'no log files given' if @log_files.empty? raise 'invalid log file given' unless @log_files.all?{|file| File.readable? file} process_options rescue puts 'Error: ' + $! return false end true end # Performs post-parse processing on options def process_options $visualization_config = @options end def output_options puts 'Options:' @options.marshal_dump.sort{|a,b| a[0].to_s <=> b[0].to_s}.each do |name, val| puts " #{name} = #{val}" end end # True if required arguments were provided def arguments_valid? video_formats = %w[avi mpg mp4] is_video_format = video_formats.any?{ |video_format| video_format == @options.output_format.downcase } return false if !@options.animate && is_video_format return false if @options.animate && !is_video_format true end def process_arguments # TODO - place in local vars, etc end def output_help puts @opts.help end def output_version puts "#{File.basename(__FILE__)} version #{VERSION}" end def process_command # TODO - do whatever this app does #process_standard_input # [Optional] - visualize @log_files + ApacheLogVisualizer.new(@log_files).visualize end def process_standard_input input = @stdin.read # TODO - process input end end # Create and run the application app = App.new(ARGV, STDIN) app.run diff --git a/lib/ip-world-map/apache_log_visualizer.rb b/lib/ip-world-map/apache_log_visualizer.rb index dd5e66e..1e76bae 100644 --- a/lib/ip-world-map/apache_log_visualizer.rb +++ b/lib/ip-world-map/apache_log_visualizer.rb @@ -1,71 +1,74 @@ -#coordinates_home = [11.6220338, 48.1276458] # Munich -#coordinates_home = [13.4114943, 52.5234802] # Berlin -#coordinates_home = [12.3387844, 45.4343363] # Venezia +class ApacheLogVisualizer -def detect_time_format times - some_samples = times.sort[0..99] - smallest_period = some_samples.each_cons(2).collect{ |time1, time2| (time1 - time2).abs }.min || 1 + def initialize log_files + @log_files = log_files + end - return '%b %d %Y %H:%M' if smallest_period < 3600 # scale: minutes - return '%b %d %Y %H:00' if smallest_period < 86400 # scale: hours - return '%b %d %Y' # scale: days -end + def detect_time_format times + some_samples = times.sort[0..99] + smallest_period = some_samples.each_cons(2).collect{ |time1, time2| (time1 - time2).abs }.min || 1 -def access_image log_files - analyzer = ApacheLogAnalyzer.new(log_files) - details = analyzer.analyze - positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } + return '%b %d %Y %H:%M' if smallest_period < 3600 # scale: minutes + return '%b %d %Y %H:00' if smallest_period < 86400 # scale: hours + return '%b %d %Y' # scale: days + end - visualization = Visualization.new - image = visualization.draw_positions(positions) - save_image image -end + def generate_image + analyzer = ApacheLogAnalyzer.new(@log_files) + details = analyzer.analyze + positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } -def access_animation log_files - analyzer = ApacheLogAnalyzer.new(log_files) - details = analyzer.analyze - grouped_details = analyzer.group_by_time(details, $visualization_config.group_seconds) + visualization = Visualization.new + image = visualization.draw_positions(positions) + save_image image + end - animation = Magick::ImageList.new - visualization = Visualization.new - time_format = $visualization_config.time_format || detect_time_format(grouped_details.keys) - frame_number = 0 + def generate_animation + analyzer = ApacheLogAnalyzer.new(@log_files) + details = analyzer.analyze + grouped_details = analyzer.group_by_time(details, $visualization_config.group_seconds) - puts "\nGenerating frames:" if $visualization_config.verbose - grouped_details.sort.each do |time, details| - frame_number += 1 - visualization.new_frame - positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } - p [time, details.size, positions.size] if $visualization_config.verbose - image = visualization.draw_positions(positions) + animation = Magick::ImageList.new + visualization = Visualization.new + time_format = $visualization_config.time_format || detect_time_format(grouped_details.keys) + frame_number = 0 + + puts "\nGenerating frames:" if $visualization_config.verbose + grouped_details.sort.each do |time, details| + frame_number += 1 + visualization.new_frame + positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } + p [time, details.size, positions.size] if $visualization_config.verbose + image = visualization.draw_positions(positions) - InformationDrawer.new.draw_info(image, visualization, time.strftime(time_format)) - save_image image, frame_number + InformationDrawer.new.draw_info(image, visualization, time.strftime(time_format)) + save_image image, frame_number + end + + render_frames_as_video end - create_animation -end + def save_image image, frame_number = 0 + if $visualization_config.animate + image.write "animation.#{'%09d' % frame_number}.bmp" + else + image.write "snapshot.#{$visualization_config.output_format}" + end + end -def save_image image, frame_number = 0 - if $visualization_config.animate - image.write "animation.#{'%09d' % frame_number}.bmp" - else - image.write "snapshot.#{$visualization_config.output_format}" + def render_frames_as_video + puts "\nGenerating video:" if $visualization_config.verbose + output = `ffmpeg -r #{$visualization_config.frames_per_second} -qscale 1 -y -i animation.%09d.bmp animation.#{$visualization_config.output_format} 2>&1` + puts output if $visualization_config.verbose + raise 'could not create the animation' unless $?.exitstatus == 0 end -end - -def create_animation - puts "\nGenerating video:" if $visualization_config.verbose - output = `ffmpeg -r #{$visualization_config.frames_per_second} -qscale 1 -y -i animation.%09d.bmp animation.#{$visualization_config.output_format} 2>&1` - puts output if $visualization_config.verbose - raise 'could not create the animation' unless $?.exitstatus == 0 -end -def visualize log_files - if $visualization_config.animate - access_animation(log_files) - else - access_image(log_files) + def visualize + if $visualization_config.animate + generate_animation + else + generate_image + end end end
darxriggs/ip-world-map
ee6cfca5087eccf354cdcbb7dc190c25bee32cf0
implemented coordinate quantization -> huge speedup
diff --git a/lib/ip-world-map/visualization.rb b/lib/ip-world-map/visualization.rb index eee54b0..c4e6a56 100644 --- a/lib/ip-world-map/visualization.rb +++ b/lib/ip-world-map/visualization.rb @@ -1,84 +1,81 @@ require 'rubygems' require 'RMagick' class Visualization attr_accessor :position_quantization_in_degrees, :circle_radius def initialize @map_filename = $visualization_config.map_filename @raw_image = Magick::ImageList.new(@map_filename).first if $visualization_config.map_width || $visualization_config.map_height width = $visualization_config.map_width || @raw_image.columns height = $visualization_config.map_height || @raw_image.rows @raw_image.resize! width, height end new_frame - @position_quantization_in_degrees = 10.0 + @position_quantization_in_degrees = 0 @opacity_visibility_threshold = 0.1 @circle_radius = (map_size[:width] ** 1.25) / (map_size[:width] * $visualization_config.fill_dot_scale).to_f - @points = [] + @points = {} end def map_size @map_size ||= { :width => @frame.columns, :height => @frame.rows } end def scale @scale ||= { :x => 360.0 / map_size[:width], :y => 180.0 / map_size[:height] } end def x_y_from_longitude_latitude longitude, latitude [ (180 + longitude) / scale[:x], (90 - latitude) / scale[:y] ] end def circle_parameters center_x, center_y [ center_x, center_y, center_x + circle_radius, center_y ] end - def quantize_position position + def quantize_position *position return position if @position_quantization_in_degrees == 0 position.collect{ |element| element - element.remainder(@position_quantization_in_degrees) } end - def quantize_positions positions - positions.collect{ |position| quantize_position(position) } - end - def select_visible_points points - points.select{ |point| point.opacity >= @opacity_visibility_threshold } + #points.select{ |point| point.opacity >= @opacity_visibility_threshold } + selected_points = {} + points.each{ |key, point| selected_points[key] = point if point.opacity >= @opacity_visibility_threshold } end def draw_positions positions_lon_lat @draw.fill($visualization_config.fill_dot_color) - new_points = positions_lon_lat.collect do |longitude, latitude| + new_points = {} + positions_lon_lat.each do |longitude, latitude| x, y = x_y_from_longitude_latitude(longitude, latitude) - PointInTime.new(x, y, $visualization_config.fill_dot_opacity, $visualization_config.fill_dot_lifetime) + x, y = quantize_position(x, y) + new_points[[x,y]] = PointInTime.new(x, y, $visualization_config.fill_dot_opacity, $visualization_config.fill_dot_lifetime) end - @points = @points.concat(new_points) @points = select_visible_points(@points) -# positions = quantize_positions(@positions) - points = @points + @points.merge!(new_points) - points.each do |point| + @points.each do |key, point| @draw.fill_opacity(point.opacity) @draw.circle(*circle_parameters(point.x, point.y)) point.age end @draw.draw(@frame) - @frame end def display @frame.display end def new_frame @draw = Magick::Draw.new @frame = @raw_image.clone end end
darxriggs/ip-world-map
5efc20ae746a2a23130eae594b584fcbc774d8e7
removed useless showing of start & end time
diff --git a/bin/ip-world-map b/bin/ip-world-map index a310613..00e33be 100755 --- a/bin/ip-world-map +++ b/bin/ip-world-map @@ -1,198 +1,196 @@ #!/usr/bin/env ruby require 'rubygems' require 'optparse' require 'ostruct' require 'date' require 'ip-world-map' class App VERSION = '0.0.1' attr_reader :options def initialize arguments, stdin @arguments = arguments @stdin = stdin set_defaults end def run if parsed_arguments? && arguments_valid? - puts "Start at #{DateTime.now}\n\n" if @options.verbose output_options if @options.verbose process_arguments process_command - puts "\nFinished at #{DateTime.now}" if @options.verbose else output_help exit 1 end end protected def set_defaults @options = OpenStruct.new({ :verbose => false, :quiet => false, :map_filename => File.join(File.dirname(__FILE__), '..' , 'resources', 'maps', 'earthmap-1920x960.tif'), :map_width => 800, :map_height => 400, :frames_per_second => 25, :fill_dot_color => 'red', :fill_dot_scale => 10, :fill_dot_opacity => 1.0, :fill_dot_lifetime => 15, :time_format => nil, :group_seconds => 24 * 1 * 60 * 60, :output_format => 'mpg', :animate => true }) end def parsed_arguments? @opts = opts = OptionParser.new opts.banner = 'Usage: ip-world-map [options] log_file1 [logfile2] ...' opts.on('--version', 'Display the version') do output_version exit 0 end opts.on('-h', '--help', 'Display this help message') do output_help exit 0 end opts.on('-v', '--verbose', 'Verbose output') do @options.verbose = true end opts.on('--map-filename VALUE', 'The image to use as background') do |filename| raise 'invalid map file' unless File.readable? filename @options.map_filename = filename end opts.on('--resolution VALUE', '(eg.: 640x480)') do |resolution| raise 'invalid resolution format' unless resolution =~ /^[0-9]+x[0-9]+$/ width, height = resolution.split('x').collect{|v| v.to_i} @options.map_width = width @options.map_height = height end opts.on('--fps VALUE', 'Animation frames per second (eg.: 25)') do |fps| raise 'invalid fps format' unless fps =~ /^[1-9][0-9]*$/ @options.frames_per_second = fps.to_i end opts.on('--fill-dot-color VALUE', "(eg.: red, 'rgb(255,0,0)', '#FF0000')") do |color| Magick::Pixel.from_color color rescue raise 'invalid color (see help for examples)' @options.fill_dot_color = color end opts.on('--fill-dot-scale VALUE', '(eg.: 10.0)') do |scale| raise 'invalid dot scale' unless scale =~ /^[1-9][0-9]*([.][0-9]*)?$/ @options.fill_dot_scale = scale.to_f end opts.on('--fill-dot-opacity VALUE', 'range 0.0-1.0 (eg.: 0.0, 0.5, 1.0)') do |opacity| raise 'invalid dot opacity' unless opacity =~ /^(0([.][0-9]*)?|1([.]0*)?)$/ @options.fill_dot_opacity = opacity.to_f end opts.on('--fill-dot-lifetime VALUE', '(eg.: 15)') do |lifetime| raise 'invalid dot lifetime' unless lifetime =~ /^[1-9][0-9]*$/ @options.fill_dot_lifetime = lifetime.to_i end opts.on('--time-slot VALUE', 'real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day)') do |slot| raise 'invalid time slot' unless slot =~ /^[1-9][0-9]*(sec|min|hour|day)s?$/ value = slot.scan(/[0-9]+/)[0].to_i unit = slot.scan(/[a-z]+[^s]/)[0] unit2secs = {'sec' => 1, 'min' => 60, 'hour' => 60*60, 'day' => 24*60*60} @options.group_seconds = value * unit2secs[unit] end # TODO # opts.on('--time-format', 'gets auto-detected if not specified') { |v| @options.time_format = v } opts.on('--output-format VALUE', 'one out of many image formats (eg.: png, jpg, gif) or video formats: avi, mpg, mp4') do |format| # accepted_formats = %w[png gif jpg tif bmp avi mpg mp4] # raise 'invalid output format' unless accepted_formats.include? format video_formats = %w[avi mpg mp4] is_supported = Magick.formats.any?{ |supported_format, properties| supported_format.upcase == format.upcase && properties.include?('w') } is_supported |= video_formats.any?{ |supported_format| supported_format.upcase == format.upcase } raise 'invalid output format' unless is_supported @options.output_format = format end opts.on('--[no-]animate', 'generate an image or a video') do |animate| @options.animate = animate end begin opts.parse!(@arguments) @log_files = Dir.glob(@arguments) raise 'no log files given' if @log_files.empty? raise 'invalid log file given' unless @log_files.all?{|file| File.readable? file} process_options rescue puts 'Error: ' + $! return false end true end # Performs post-parse processing on options def process_options $visualization_config = @options end def output_options puts 'Options:' @options.marshal_dump.sort{|a,b| a[0].to_s <=> b[0].to_s}.each do |name, val| puts " #{name} = #{val}" end end # True if required arguments were provided def arguments_valid? video_formats = %w[avi mpg mp4] is_video_format = video_formats.any?{ |video_format| video_format == @options.output_format.downcase } return false if !@options.animate && is_video_format return false if @options.animate && !is_video_format true end def process_arguments # TODO - place in local vars, etc end def output_help puts @opts.help end def output_version puts "#{File.basename(__FILE__)} version #{VERSION}" end def process_command # TODO - do whatever this app does #process_standard_input # [Optional] visualize @log_files end def process_standard_input input = @stdin.read # TODO - process input end end # Create and run the application app = App.new(ARGV, STDIN) app.run
darxriggs/ip-world-map
8695489b63ea3a87c8f45965489921e0c623008b
refactored LogAnalyzer
diff --git a/lib/ip-world-map/log_analyzer.rb b/lib/ip-world-map/log_analyzer.rb index a2412b8..75b7313 100644 --- a/lib/ip-world-map/log_analyzer.rb +++ b/lib/ip-world-map/log_analyzer.rb @@ -1,60 +1,59 @@ class LogAnalyzer attr_accessor :host_coordinates def initialize *filenames @filenames = filenames.flatten.sort.uniq @ip_lookup_service = IpLookupService.new @ip_lookup_service.load_coordinates end def analyze details = [] @filenames.each do |filename| puts filename - FileUtils.open(filename) do |file| - lines = file.readlines - lines.each{ |line| details << details_from_line(line) } + FileUtils.open(filename).each_line do |line| + details << details_from_line(line) end end hosts = details.collect{|detail| detail[:host]} coordinates = @ip_lookup_service.coordinates_for_hosts(hosts) details.collect! do |detail| detail[:coordinates] = coordinates[detail[:host]] detail end details end def details_from_line line host = extract_host_from_line(line) time = extract_time_from_line(line) { :time => time, :host => host } end def calculate_oldest_time details details.min{ |a, b| a[:time] <=> b[:time] }[:time] end def group_by_time details, slot_in_seconds return {} unless details && slot_in_seconds details_per_slot = {} # TODO: maybe assign empty arrays to missing slots where no traffic was detected details.each do |detail| slot_start_time = calculate_slot_start_time(detail[:time], slot_in_seconds) details_per_slot[slot_start_time] ||= [] details_per_slot[slot_start_time] << detail end details_per_slot end def calculate_slot_start_time time, slot_in_seconds Time.at(time.tv_sec - (time.tv_sec % slot_in_seconds)) end end
darxriggs/ip-world-map
8d191543e190029e68c932b1ac85c67aa9037189
refactored PointInTime
diff --git a/lib/ip-world-map/point_in_time.rb b/lib/ip-world-map/point_in_time.rb index a09cf82..54e983d 100644 --- a/lib/ip-world-map/point_in_time.rb +++ b/lib/ip-world-map/point_in_time.rb @@ -1,23 +1,23 @@ class PointInTime attr_reader :x, :y def initialize x, y, initial_opacity, lifetime @x, @y = x, y @time = 0 @decay = Decay.new(initial_opacity, lifetime) end def opacity_in_time time @time = time if time - @decay.value(@time) + opacity end def opacity @decay.value(@time) end def age @time += 1 end end
darxriggs/ip-world-map
9597d9158a452fa5c02c879e010e8ad60535402d
fixed caching for parallel HTTP request implementation - now the IP is only looked up if no data exists yet
diff --git a/lib/ip-world-map/ip_lookup_service.rb b/lib/ip-world-map/ip_lookup_service.rb index 9d13cc2..538cca0 100644 --- a/lib/ip-world-map/ip_lookup_service.rb +++ b/lib/ip-world-map/ip_lookup_service.rb @@ -1,67 +1,69 @@ require 'net/http' require 'typhoeus' require 'yaml' class IpLookupService def initialize filename = nil @filename = filename || File.join(File.dirname(__FILE__), '..', '..', 'resources', 'coordinates.yml') reset end def reset @host_coordinates = {} @host_ips = {} end def coordinates_for_hosts hosts uniq_hosts = hosts.uniq uniq_hosts.each do |host| @host_ips[host] ||= IPSocket.getaddress(host) rescue nil end hydra = Typhoeus::Hydra.new uniq_hosts.each do |host| - request = Typhoeus::Request.new("http://api.hostip.info/get_html.php?position=true&ip=#{@host_ips[host]}") - request.on_complete do |response| - @host_coordinates[host] = extract_longitude_and_latitude(response.body) + unless @host_coordinates[host] + request = Typhoeus::Request.new("http://api.hostip.info/get_html.php?position=true&ip=#{@host_ips[host]}") + request.on_complete do |response| + @host_coordinates[host] = extract_longitude_and_latitude(response.body) + end + hydra.queue(request) end - hydra.queue(request) end hydra.run @host_coordinates end def coordinates_for_host host unless @host_coordinates[host] @host_ips[host] ||= IPSocket.getaddress(host) rescue nil response = Net::HTTP.get('api.hostip.info', "/get_html.php?position=true&ip=#{@host_ips[host]}") @host_coordinates[host] = extract_longitude_and_latitude(response) end @host_coordinates[host] end def extract_longitude_and_latitude string latitude = string.match(/Latitude: (-?[0-9.]+)/)[1].to_f rescue nil longitude = string.match(/Longitude: (-?[0-9.]+)/)[1].to_f rescue nil [longitude, latitude] end def save_coordinates File.open(@filename, 'w'){ |f| f.write @host_coordinates.to_yaml } end def load_coordinates @host_coordinates = YAML.load_file(@filename) if File.readable? @filename end def stats unknown_coordinates, known_coordinates = @host_coordinates.partition{ |ip, coords| coords.include? nil } { :unknown_coordinates => unknown_coordinates.size, :known_coordinates => known_coordinates.size } end end
darxriggs/ip-world-map
a7c2f84d5f52cead5c0fe5486f6b125769a19f22
fixed default output format - changed from gif to mpg since animated gif is not supported anymore
diff --git a/bin/ip-world-map b/bin/ip-world-map index 4eebb57..a310613 100755 --- a/bin/ip-world-map +++ b/bin/ip-world-map @@ -1,198 +1,198 @@ #!/usr/bin/env ruby require 'rubygems' require 'optparse' require 'ostruct' require 'date' require 'ip-world-map' class App VERSION = '0.0.1' attr_reader :options def initialize arguments, stdin @arguments = arguments @stdin = stdin set_defaults end def run if parsed_arguments? && arguments_valid? puts "Start at #{DateTime.now}\n\n" if @options.verbose output_options if @options.verbose process_arguments process_command puts "\nFinished at #{DateTime.now}" if @options.verbose else output_help exit 1 end end protected def set_defaults @options = OpenStruct.new({ :verbose => false, :quiet => false, :map_filename => File.join(File.dirname(__FILE__), '..' , 'resources', 'maps', 'earthmap-1920x960.tif'), :map_width => 800, :map_height => 400, :frames_per_second => 25, :fill_dot_color => 'red', :fill_dot_scale => 10, :fill_dot_opacity => 1.0, :fill_dot_lifetime => 15, :time_format => nil, :group_seconds => 24 * 1 * 60 * 60, - :output_format => 'gif', + :output_format => 'mpg', :animate => true }) end def parsed_arguments? @opts = opts = OptionParser.new opts.banner = 'Usage: ip-world-map [options] log_file1 [logfile2] ...' opts.on('--version', 'Display the version') do output_version exit 0 end opts.on('-h', '--help', 'Display this help message') do output_help exit 0 end opts.on('-v', '--verbose', 'Verbose output') do @options.verbose = true end opts.on('--map-filename VALUE', 'The image to use as background') do |filename| raise 'invalid map file' unless File.readable? filename @options.map_filename = filename end opts.on('--resolution VALUE', '(eg.: 640x480)') do |resolution| raise 'invalid resolution format' unless resolution =~ /^[0-9]+x[0-9]+$/ width, height = resolution.split('x').collect{|v| v.to_i} @options.map_width = width @options.map_height = height end opts.on('--fps VALUE', 'Animation frames per second (eg.: 25)') do |fps| raise 'invalid fps format' unless fps =~ /^[1-9][0-9]*$/ @options.frames_per_second = fps.to_i end opts.on('--fill-dot-color VALUE', "(eg.: red, 'rgb(255,0,0)', '#FF0000')") do |color| Magick::Pixel.from_color color rescue raise 'invalid color (see help for examples)' @options.fill_dot_color = color end opts.on('--fill-dot-scale VALUE', '(eg.: 10.0)') do |scale| raise 'invalid dot scale' unless scale =~ /^[1-9][0-9]*([.][0-9]*)?$/ @options.fill_dot_scale = scale.to_f end opts.on('--fill-dot-opacity VALUE', 'range 0.0-1.0 (eg.: 0.0, 0.5, 1.0)') do |opacity| raise 'invalid dot opacity' unless opacity =~ /^(0([.][0-9]*)?|1([.]0*)?)$/ @options.fill_dot_opacity = opacity.to_f end opts.on('--fill-dot-lifetime VALUE', '(eg.: 15)') do |lifetime| raise 'invalid dot lifetime' unless lifetime =~ /^[1-9][0-9]*$/ @options.fill_dot_lifetime = lifetime.to_i end opts.on('--time-slot VALUE', 'real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day)') do |slot| raise 'invalid time slot' unless slot =~ /^[1-9][0-9]*(sec|min|hour|day)s?$/ value = slot.scan(/[0-9]+/)[0].to_i unit = slot.scan(/[a-z]+[^s]/)[0] unit2secs = {'sec' => 1, 'min' => 60, 'hour' => 60*60, 'day' => 24*60*60} @options.group_seconds = value * unit2secs[unit] end # TODO # opts.on('--time-format', 'gets auto-detected if not specified') { |v| @options.time_format = v } opts.on('--output-format VALUE', 'one out of many image formats (eg.: png, jpg, gif) or video formats: avi, mpg, mp4') do |format| # accepted_formats = %w[png gif jpg tif bmp avi mpg mp4] # raise 'invalid output format' unless accepted_formats.include? format video_formats = %w[avi mpg mp4] is_supported = Magick.formats.any?{ |supported_format, properties| supported_format.upcase == format.upcase && properties.include?('w') } is_supported |= video_formats.any?{ |supported_format| supported_format.upcase == format.upcase } raise 'invalid output format' unless is_supported @options.output_format = format end opts.on('--[no-]animate', 'generate an image or a video') do |animate| @options.animate = animate end begin opts.parse!(@arguments) @log_files = Dir.glob(@arguments) raise 'no log files given' if @log_files.empty? raise 'invalid log file given' unless @log_files.all?{|file| File.readable? file} process_options rescue puts 'Error: ' + $! return false end true end # Performs post-parse processing on options def process_options $visualization_config = @options end def output_options puts 'Options:' @options.marshal_dump.sort{|a,b| a[0].to_s <=> b[0].to_s}.each do |name, val| puts " #{name} = #{val}" end end # True if required arguments were provided def arguments_valid? video_formats = %w[avi mpg mp4] is_video_format = video_formats.any?{ |video_format| video_format == @options.output_format.downcase } return false if !@options.animate && is_video_format return false if @options.animate && !is_video_format true end def process_arguments # TODO - place in local vars, etc end def output_help puts @opts.help end def output_version puts "#{File.basename(__FILE__)} version #{VERSION}" end def process_command # TODO - do whatever this app does #process_standard_input # [Optional] visualize @log_files end def process_standard_input input = @stdin.read # TODO - process input end end # Create and run the application app = App.new(ARGV, STDIN) app.run
darxriggs/ip-world-map
760d239c3ae8564d1324ad715bece8ca48401e68
added utf-8 encoding comment to make ruby1.9 work
diff --git a/Rakefile b/Rakefile index e5291e5..f74d9ef 100644 --- a/Rakefile +++ b/Rakefile @@ -1,39 +1,40 @@ +# -*- coding: utf-8 -*- require 'rubygems' require 'spec/version' require 'spec/rake/spectask' require 'rake/gempackagetask' Spec::Rake::SpecTask.new(:spec) do |t| t.spec_files = FileList['spec/**/*.rb'] t.rcov = false t.rcov_opts = ['--exclude', 'spec'] t.verbose = true end spec = Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.summary = 'A tool to generate images/videos of user locations based on Apache log files.' s.name = 'ip-world-map' s.version = '0.0.1' s.requirements << 'RMagick' s.require_path = 'lib' s.bindir = 'bin' s.executables = ['ip-world-map'] s.files = FileList['{lib,spec}/**/*'].to_a + ['Rakefile'] + ['resources/maps/earthmap-1920x960.tif'] s.description = s.summary s.author = 'René Scheibe' s.email = 'rene.scheibe@gmail.com' end Rake::GemPackageTask.new(spec) do |pkg| pkg.need_tar = false end task :install_gem => :package do `sudo gem install pkg/*.gem` end task :default => :install_gem
darxriggs/ip-world-map
ec2f1bfb6bb2ad022b295f26ce652a54d7d6e899
implemented parallel requests for IP -> geo-location lookup
diff --git a/lib/ip-world-map/ip_lookup_service.rb b/lib/ip-world-map/ip_lookup_service.rb index d8c7120..9d13cc2 100644 --- a/lib/ip-world-map/ip_lookup_service.rb +++ b/lib/ip-world-map/ip_lookup_service.rb @@ -1,43 +1,67 @@ require 'net/http' +require 'typhoeus' require 'yaml' class IpLookupService def initialize filename = nil @filename = filename || File.join(File.dirname(__FILE__), '..', '..', 'resources', 'coordinates.yml') reset end def reset @host_coordinates = {} @host_ips = {} end + def coordinates_for_hosts hosts + uniq_hosts = hosts.uniq + + uniq_hosts.each do |host| + @host_ips[host] ||= IPSocket.getaddress(host) rescue nil + end + + hydra = Typhoeus::Hydra.new + uniq_hosts.each do |host| + request = Typhoeus::Request.new("http://api.hostip.info/get_html.php?position=true&ip=#{@host_ips[host]}") + request.on_complete do |response| + @host_coordinates[host] = extract_longitude_and_latitude(response.body) + end + hydra.queue(request) + end + hydra.run + + @host_coordinates + end + def coordinates_for_host host unless @host_coordinates[host] - @host_ips[host] ||= IPSocket.getaddr(host) rescue nil - + @host_ips[host] ||= IPSocket.getaddress(host) rescue nil response = Net::HTTP.get('api.hostip.info', "/get_html.php?position=true&ip=#{@host_ips[host]}") - latitude = response.match(/Latitude: (-?[0-9.]+)/)[1].to_f rescue nil - longitude = response.match(/Longitude: (-?[0-9.]+)/)[1].to_f rescue nil - @host_coordinates[host] = [longitude, latitude] + @host_coordinates[host] = extract_longitude_and_latitude(response) end @host_coordinates[host] end + def extract_longitude_and_latitude string + latitude = string.match(/Latitude: (-?[0-9.]+)/)[1].to_f rescue nil + longitude = string.match(/Longitude: (-?[0-9.]+)/)[1].to_f rescue nil + [longitude, latitude] + end + def save_coordinates File.open(@filename, 'w'){ |f| f.write @host_coordinates.to_yaml } end def load_coordinates @host_coordinates = YAML.load_file(@filename) if File.readable? @filename end def stats unknown_coordinates, known_coordinates = @host_coordinates.partition{ |ip, coords| coords.include? nil } { :unknown_coordinates => unknown_coordinates.size, :known_coordinates => known_coordinates.size } end end diff --git a/lib/ip-world-map/log_analyzer.rb b/lib/ip-world-map/log_analyzer.rb index b3ee801..a2412b8 100644 --- a/lib/ip-world-map/log_analyzer.rb +++ b/lib/ip-world-map/log_analyzer.rb @@ -1,56 +1,60 @@ class LogAnalyzer attr_accessor :host_coordinates def initialize *filenames @filenames = filenames.flatten.sort.uniq @ip_lookup_service = IpLookupService.new @ip_lookup_service.load_coordinates end - def details_from_line line - host = extract_host_from_line(line) - time = extract_time_from_line(line) - coordinates = @ip_lookup_service.coordinates_for_host(host) - - { :time => time, :host => host, :coordinates => coordinates } - end - def analyze details = [] @filenames.each do |filename| puts filename FileUtils.open(filename) do |file| lines = file.readlines - lines.each do |line| - details << details_from_line(line) - end + lines.each{ |line| details << details_from_line(line) } end end + hosts = details.collect{|detail| detail[:host]} + coordinates = @ip_lookup_service.coordinates_for_hosts(hosts) + + details.collect! do |detail| + detail[:coordinates] = coordinates[detail[:host]] + detail + end + details end + def details_from_line line + host = extract_host_from_line(line) + time = extract_time_from_line(line) + { :time => time, :host => host } + end + def calculate_oldest_time details details.min{ |a, b| a[:time] <=> b[:time] }[:time] end def group_by_time details, slot_in_seconds return {} unless details && slot_in_seconds details_per_slot = {} # TODO: maybe assign empty arrays to missing slots where no traffic was detected details.each do |detail| slot_start_time = calculate_slot_start_time(detail[:time], slot_in_seconds) details_per_slot[slot_start_time] ||= [] details_per_slot[slot_start_time] << detail end details_per_slot end def calculate_slot_start_time time, slot_in_seconds Time.at(time.tv_sec - (time.tv_sec % slot_in_seconds)) end end
darxriggs/ip-world-map
9a0e02f8d52a5ebb7999156569ade384ad993dae
refactored code to use IPSocket instead of Socket for hostname -> IP lookup
diff --git a/lib/ip-world-map/ip_lookup_service.rb b/lib/ip-world-map/ip_lookup_service.rb index f353014..d8c7120 100644 --- a/lib/ip-world-map/ip_lookup_service.rb +++ b/lib/ip-world-map/ip_lookup_service.rb @@ -1,51 +1,43 @@ require 'net/http' require 'yaml' class IpLookupService - def self.ip_for_host host - is_ip?(host) ? host : Socket.getaddrinfo(host, nil, Socket::AF_INET)[0][3] rescue nil - end - - def self.is_ip? string - /^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$/.match(string) != nil - end - def initialize filename = nil @filename = filename || File.join(File.dirname(__FILE__), '..', '..', 'resources', 'coordinates.yml') reset end def reset @host_coordinates = {} @host_ips = {} end def coordinates_for_host host unless @host_coordinates[host] - @host_ips[host] ||= IpLookupService.ip_for_host(host) + @host_ips[host] ||= IPSocket.getaddr(host) rescue nil response = Net::HTTP.get('api.hostip.info', "/get_html.php?position=true&ip=#{@host_ips[host]}") latitude = response.match(/Latitude: (-?[0-9.]+)/)[1].to_f rescue nil longitude = response.match(/Longitude: (-?[0-9.]+)/)[1].to_f rescue nil @host_coordinates[host] = [longitude, latitude] end @host_coordinates[host] end def save_coordinates File.open(@filename, 'w'){ |f| f.write @host_coordinates.to_yaml } end def load_coordinates @host_coordinates = YAML.load_file(@filename) if File.readable? @filename end def stats unknown_coordinates, known_coordinates = @host_coordinates.partition{ |ip, coords| coords.include? nil } { :unknown_coordinates => unknown_coordinates.size, :known_coordinates => known_coordinates.size } end end diff --git a/spec/ip-world-map/ip_lookup_service.rb b/spec/ip-world-map/ip_lookup_service.rb index 762e043..724d3f5 100644 --- a/spec/ip-world-map/ip_lookup_service.rb +++ b/spec/ip-world-map/ip_lookup_service.rb @@ -1,50 +1,37 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper.rb') describe IpLookupService do - describe 'IP check' do - it 'should check if a given string is an IP' do - IpLookupService.is_ip?('1.1.1.1').should be true - IpLookupService.is_ip?('1.1.1.1234').should be false - IpLookupService.is_ip?('no IP').should be false - end - end - - describe 'hostname -> IP resolval' do - it 'should return the IP for an existing hostname' do - stubbed_result = [['AF_INET', 0, 'domain.net', '1.1.1.1', 2, 1, 6], - ['AF_INET', 0, 'domain.net', '2.2.2.2', 2, 2, 0]] - Socket.stub!(:getaddrinfo).and_return(stubbed_result) - - IpLookupService.ip_for_host('existing hostname').should match /^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$/ - end + describe 'hostname -> coordinates resolval' do + it 'should return the coordinates for an IP' do + stubbed_result = "Country: GERMANY (DE)\nCity: Berlin\n\nLatitude: 52.5\nLongitude: 13.4167\nIP: 1.1.1.1\n" + Net::HTTP.stub!(:get).and_return(stubbed_result) - it 'should return the IP if an IP is given as hostname' do - IpLookupService.ip_for_host('1.1.1.1').should == '1.1.1.1' + IpLookupService.new.coordinates_for_host('1.1.1.1').should == [13.4167, 52.5] end - it 'should handle the case that no IP can be resolved for a hostname' do - Socket.stub!(:getaddrinfo).and_raise(SocketError) + it 'should return the coordinates for a hostname' do + stubbed_result = "Country: GERMANY (DE)\nCity: Berlin\n\nLatitude: 52.5\nLongitude: 13.4167\nIP: 1.1.1.1\n" + Net::HTTP.stub!(:get).and_return(stubbed_result) + IPSocket.stub!(:getaddr).and_return('1.1.1.1') - IpLookupService.ip_for_host('non-existing hostname').should be nil + IpLookupService.new.coordinates_for_host('some hostname').should == [13.4167, 52.5] end - end - describe 'hostname -> coordinates resolval' do - it 'should return the coordinates for an IP' do - stubbed_result = "Country: GERMANY (DE)\nCity: Berlin\n\nLatitude: 52.5\nLongitude: 13.4167\nIP: 1.1.1.1\n" + it 'should handle the case that no IP can be resolved for a hostname' do + stubbed_result = "Country: GERMANY (DE)\nCity: Berlin\n\nLatitude: \nLongitude: \nIP: 1.1.1.1\n" Net::HTTP.stub!(:get).and_return(stubbed_result) - Socket.stub!(:getaddrinfo) + IPSocket.stub!(:getaddrinfo).and_raise(SocketError) - IpLookupService.new.coordinates_for_host('some hostname').should == [13.4167, 52.5] + IpLookupService.new.coordinates_for_host('some hostname').should == [nil, nil] end - it 'should handle the case that no coordinates can be resolved for an IP' do + it 'should handle the case that no coordinates can be resolved for a hostname' do stubbed_result = "Country: GERMANY (DE)\nCity: Berlin\n\nLatitude: \nLongitude: \nIP: 1.1.1.1\n" Net::HTTP.stub!(:get).and_return(stubbed_result) - Socket.stub!(:getaddrinfo) + IPSocket.stub!(:getaddr) IpLookupService.new.coordinates_for_host('some hostname').should == [nil, nil] end end end
darxriggs/ip-world-map
9847c89adcb642825b0696b74c0b0f6ac681016a
added tests for IpLookupService
diff --git a/spec/ip-world-map/ip_lookup_service.rb b/spec/ip-world-map/ip_lookup_service.rb new file mode 100644 index 0000000..762e043 --- /dev/null +++ b/spec/ip-world-map/ip_lookup_service.rb @@ -0,0 +1,50 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper.rb') + +describe IpLookupService do + describe 'IP check' do + it 'should check if a given string is an IP' do + IpLookupService.is_ip?('1.1.1.1').should be true + IpLookupService.is_ip?('1.1.1.1234').should be false + IpLookupService.is_ip?('no IP').should be false + end + end + + describe 'hostname -> IP resolval' do + it 'should return the IP for an existing hostname' do + stubbed_result = [['AF_INET', 0, 'domain.net', '1.1.1.1', 2, 1, 6], + ['AF_INET', 0, 'domain.net', '2.2.2.2', 2, 2, 0]] + Socket.stub!(:getaddrinfo).and_return(stubbed_result) + + IpLookupService.ip_for_host('existing hostname').should match /^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$/ + end + + it 'should return the IP if an IP is given as hostname' do + IpLookupService.ip_for_host('1.1.1.1').should == '1.1.1.1' + end + + it 'should handle the case that no IP can be resolved for a hostname' do + Socket.stub!(:getaddrinfo).and_raise(SocketError) + + IpLookupService.ip_for_host('non-existing hostname').should be nil + end + end + + describe 'hostname -> coordinates resolval' do + it 'should return the coordinates for an IP' do + stubbed_result = "Country: GERMANY (DE)\nCity: Berlin\n\nLatitude: 52.5\nLongitude: 13.4167\nIP: 1.1.1.1\n" + Net::HTTP.stub!(:get).and_return(stubbed_result) + Socket.stub!(:getaddrinfo) + + IpLookupService.new.coordinates_for_host('some hostname').should == [13.4167, 52.5] + end + + it 'should handle the case that no coordinates can be resolved for an IP' do + stubbed_result = "Country: GERMANY (DE)\nCity: Berlin\n\nLatitude: \nLongitude: \nIP: 1.1.1.1\n" + Net::HTTP.stub!(:get).and_return(stubbed_result) + Socket.stub!(:getaddrinfo) + + IpLookupService.new.coordinates_for_host('some hostname').should == [nil, nil] + end + end +end +
darxriggs/ip-world-map
0ef7a163348d432e7a5d04e7e387332a98e48140
cached/serialized for the IpLookupService now have to be loaded explicitly
diff --git a/lib/ip-world-map/ip_lookup_service.rb b/lib/ip-world-map/ip_lookup_service.rb index 8ccb1bd..f353014 100644 --- a/lib/ip-world-map/ip_lookup_service.rb +++ b/lib/ip-world-map/ip_lookup_service.rb @@ -1,52 +1,51 @@ require 'net/http' require 'yaml' class IpLookupService def self.ip_for_host host is_ip?(host) ? host : Socket.getaddrinfo(host, nil, Socket::AF_INET)[0][3] rescue nil end def self.is_ip? string /^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$/.match(string) != nil end def initialize filename = nil @filename = filename || File.join(File.dirname(__FILE__), '..', '..', 'resources', 'coordinates.yml') reset - load_coordinates end def reset @host_coordinates = {} @host_ips = {} end def coordinates_for_host host unless @host_coordinates[host] @host_ips[host] ||= IpLookupService.ip_for_host(host) response = Net::HTTP.get('api.hostip.info', "/get_html.php?position=true&ip=#{@host_ips[host]}") latitude = response.match(/Latitude: (-?[0-9.]+)/)[1].to_f rescue nil longitude = response.match(/Longitude: (-?[0-9.]+)/)[1].to_f rescue nil @host_coordinates[host] = [longitude, latitude] end @host_coordinates[host] end def save_coordinates File.open(@filename, 'w'){ |f| f.write @host_coordinates.to_yaml } end def load_coordinates @host_coordinates = YAML.load_file(@filename) if File.readable? @filename end def stats unknown_coordinates, known_coordinates = @host_coordinates.partition{ |ip, coords| coords.include? nil } { :unknown_coordinates => unknown_coordinates.size, :known_coordinates => known_coordinates.size } end end diff --git a/lib/ip-world-map/log_analyzer.rb b/lib/ip-world-map/log_analyzer.rb index 7b48da8..b3ee801 100644 --- a/lib/ip-world-map/log_analyzer.rb +++ b/lib/ip-world-map/log_analyzer.rb @@ -1,55 +1,56 @@ class LogAnalyzer attr_accessor :host_coordinates def initialize *filenames @filenames = filenames.flatten.sort.uniq @ip_lookup_service = IpLookupService.new + @ip_lookup_service.load_coordinates end def details_from_line line host = extract_host_from_line(line) time = extract_time_from_line(line) coordinates = @ip_lookup_service.coordinates_for_host(host) { :time => time, :host => host, :coordinates => coordinates } end def analyze details = [] @filenames.each do |filename| puts filename FileUtils.open(filename) do |file| lines = file.readlines lines.each do |line| details << details_from_line(line) end end end details end def calculate_oldest_time details details.min{ |a, b| a[:time] <=> b[:time] }[:time] end def group_by_time details, slot_in_seconds return {} unless details && slot_in_seconds details_per_slot = {} # TODO: maybe assign empty arrays to missing slots where no traffic was detected details.each do |detail| slot_start_time = calculate_slot_start_time(detail[:time], slot_in_seconds) details_per_slot[slot_start_time] ||= [] details_per_slot[slot_start_time] << detail end details_per_slot end def calculate_slot_start_time time, slot_in_seconds Time.at(time.tv_sec - (time.tv_sec % slot_in_seconds)) end end
darxriggs/ip-world-map
1be38ada3838387829483f859906c0a8b5be253e
changed some instance -> class methods
diff --git a/lib/ip-world-map/ip_lookup_service.rb b/lib/ip-world-map/ip_lookup_service.rb index 3ff2b4a..8ccb1bd 100644 --- a/lib/ip-world-map/ip_lookup_service.rb +++ b/lib/ip-world-map/ip_lookup_service.rb @@ -1,52 +1,52 @@ require 'net/http' require 'yaml' class IpLookupService + def self.ip_for_host host + is_ip?(host) ? host : Socket.getaddrinfo(host, nil, Socket::AF_INET)[0][3] rescue nil + end + + def self.is_ip? string + /^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$/.match(string) != nil + end + def initialize filename = nil @filename = filename || File.join(File.dirname(__FILE__), '..', '..', 'resources', 'coordinates.yml') reset load_coordinates end def reset @host_coordinates = {} @host_ips = {} end def coordinates_for_host host unless @host_coordinates[host] - @host_ips[host] ||= ip_for_host(host) + @host_ips[host] ||= IpLookupService.ip_for_host(host) response = Net::HTTP.get('api.hostip.info', "/get_html.php?position=true&ip=#{@host_ips[host]}") latitude = response.match(/Latitude: (-?[0-9.]+)/)[1].to_f rescue nil longitude = response.match(/Longitude: (-?[0-9.]+)/)[1].to_f rescue nil @host_coordinates[host] = [longitude, latitude] end @host_coordinates[host] end - def ip_for_host host - is_ip?(host) ? host : Socket.getaddrinfo(host, nil)[0][3] rescue nil - end - - def is_ip? string - /^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$/.match(string) != nil - end - def save_coordinates File.open(@filename, 'w'){ |f| f.write @host_coordinates.to_yaml } end def load_coordinates @host_coordinates = YAML.load_file(@filename) if File.readable? @filename end def stats unknown_coordinates, known_coordinates = @host_coordinates.partition{ |ip, coords| coords.include? nil } { :unknown_coordinates => unknown_coordinates.size, :known_coordinates => known_coordinates.size } end end
darxriggs/ip-world-map
c3656cf5e67015e9bc16155f3f8b784aa8c36ac8
cleaned specs
diff --git a/spec/ip-world-map/decay.rb b/spec/ip-world-map/decay.rb index 17ed58f..7505795 100644 --- a/spec/ip-world-map/decay.rb +++ b/spec/ip-world-map/decay.rb @@ -1,18 +1,18 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper.rb') -describe PointInTime do +describe Decay do it 'should be initialized with either Integers and/or Floats' do Decay.new(10, 5 ) Decay.new(10, 5.0) Decay.new(10.0, 5 ) Decay.new(10.0, 5.0) end it 'should return a value depending on the time' do decay = Decay.new(10, 5) - decay.value(0).should be 10 - decay.value(2).should be 0 # todo + decay.value(0).should == 10.0 + decay.value(5).should < 5.0 end end diff --git a/spec/ip-world-map/point_in_time.rb b/spec/ip-world-map/point_in_time.rb index 6bbc193..b2de136 100644 --- a/spec/ip-world-map/point_in_time.rb +++ b/spec/ip-world-map/point_in_time.rb @@ -1,20 +1,7 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper.rb') describe PointInTime do - it 'should convert currencies properly' do - Currency::convert('AUD', 'USD').should > 0 - end - - it 'raise an exception on incorrect currencies' do - lambda { Currency::convert('YYY', 'XXX') }.should raise_error(Currency::RateError) - end - - it 'should process amounts properly' do - amount = 10 - result_with_amount = Currency::convert('AUD', 'USD', amount) - result_without_amount = Currency::convert('AUD', 'USD') - - result_with_amount.should == amount * result_without_amount + it 'TODO' do end end diff --git a/spec/ip-world-map/time_format.rb b/spec/ip-world-map/time_format.rb index c2a1367..fc0c542 100644 --- a/spec/ip-world-map/time_format.rb +++ b/spec/ip-world-map/time_format.rb @@ -1,19 +1,22 @@ require File.join(File.dirname(__FILE__), '..' , 'spec_helper.rb') -describe TimeFormat do +describe 'TimeFormat' do it 'should return a minute based time format for times within an hour' do now = Time.now times = [now, now + 123456789, now + 1] +# TODO end it 'should return a hour based time format for times within a day' do now = Time.now times = [now, now + 123456789, now + 1] +# TODO end it 'should return a day based time format for times greater than a day' do now = Time.now times = [now, now + 123456789, now + 1] +# TODO end end
darxriggs/ip-world-map
808c9a5aec054c04719ab19738e71b8f08b38fdf
added spec.opts
diff --git a/spec/spec.opts b/spec/spec.opts new file mode 100644 index 0000000..59b6d39 --- /dev/null +++ b/spec/spec.opts @@ -0,0 +1,3 @@ +--color +--diff +--loadby mtime
darxriggs/ip-world-map
6d6f6fb820dcb11c68e2089fd4db6a2b53fe8e85
removed all extra brackets in method declarations
diff --git a/bin/ip-world-map b/bin/ip-world-map index 59df5c2..4eebb57 100755 --- a/bin/ip-world-map +++ b/bin/ip-world-map @@ -1,198 +1,198 @@ #!/usr/bin/env ruby require 'rubygems' require 'optparse' require 'ostruct' require 'date' require 'ip-world-map' class App VERSION = '0.0.1' attr_reader :options - def initialize(arguments, stdin) + def initialize arguments, stdin @arguments = arguments @stdin = stdin set_defaults end def run if parsed_arguments? && arguments_valid? puts "Start at #{DateTime.now}\n\n" if @options.verbose output_options if @options.verbose process_arguments process_command puts "\nFinished at #{DateTime.now}" if @options.verbose else output_help exit 1 end end protected def set_defaults @options = OpenStruct.new({ :verbose => false, :quiet => false, :map_filename => File.join(File.dirname(__FILE__), '..' , 'resources', 'maps', 'earthmap-1920x960.tif'), :map_width => 800, :map_height => 400, :frames_per_second => 25, :fill_dot_color => 'red', :fill_dot_scale => 10, :fill_dot_opacity => 1.0, :fill_dot_lifetime => 15, :time_format => nil, :group_seconds => 24 * 1 * 60 * 60, :output_format => 'gif', :animate => true }) end def parsed_arguments? @opts = opts = OptionParser.new opts.banner = 'Usage: ip-world-map [options] log_file1 [logfile2] ...' opts.on('--version', 'Display the version') do output_version exit 0 end opts.on('-h', '--help', 'Display this help message') do output_help exit 0 end opts.on('-v', '--verbose', 'Verbose output') do @options.verbose = true end opts.on('--map-filename VALUE', 'The image to use as background') do |filename| raise 'invalid map file' unless File.readable? filename @options.map_filename = filename end opts.on('--resolution VALUE', '(eg.: 640x480)') do |resolution| raise 'invalid resolution format' unless resolution =~ /^[0-9]+x[0-9]+$/ width, height = resolution.split('x').collect{|v| v.to_i} @options.map_width = width @options.map_height = height end opts.on('--fps VALUE', 'Animation frames per second (eg.: 25)') do |fps| raise 'invalid fps format' unless fps =~ /^[1-9][0-9]*$/ @options.frames_per_second = fps.to_i end opts.on('--fill-dot-color VALUE', "(eg.: red, 'rgb(255,0,0)', '#FF0000')") do |color| Magick::Pixel.from_color color rescue raise 'invalid color (see help for examples)' @options.fill_dot_color = color end opts.on('--fill-dot-scale VALUE', '(eg.: 10.0)') do |scale| raise 'invalid dot scale' unless scale =~ /^[1-9][0-9]*([.][0-9]*)?$/ @options.fill_dot_scale = scale.to_f end opts.on('--fill-dot-opacity VALUE', 'range 0.0-1.0 (eg.: 0.0, 0.5, 1.0)') do |opacity| raise 'invalid dot opacity' unless opacity =~ /^(0([.][0-9]*)?|1([.]0*)?)$/ @options.fill_dot_opacity = opacity.to_f end opts.on('--fill-dot-lifetime VALUE', '(eg.: 15)') do |lifetime| raise 'invalid dot lifetime' unless lifetime =~ /^[1-9][0-9]*$/ @options.fill_dot_lifetime = lifetime.to_i end opts.on('--time-slot VALUE', 'real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day)') do |slot| raise 'invalid time slot' unless slot =~ /^[1-9][0-9]*(sec|min|hour|day)s?$/ value = slot.scan(/[0-9]+/)[0].to_i unit = slot.scan(/[a-z]+[^s]/)[0] unit2secs = {'sec' => 1, 'min' => 60, 'hour' => 60*60, 'day' => 24*60*60} @options.group_seconds = value * unit2secs[unit] end # TODO # opts.on('--time-format', 'gets auto-detected if not specified') { |v| @options.time_format = v } opts.on('--output-format VALUE', 'one out of many image formats (eg.: png, jpg, gif) or video formats: avi, mpg, mp4') do |format| # accepted_formats = %w[png gif jpg tif bmp avi mpg mp4] # raise 'invalid output format' unless accepted_formats.include? format video_formats = %w[avi mpg mp4] is_supported = Magick.formats.any?{ |supported_format, properties| supported_format.upcase == format.upcase && properties.include?('w') } is_supported |= video_formats.any?{ |supported_format| supported_format.upcase == format.upcase } raise 'invalid output format' unless is_supported @options.output_format = format end opts.on('--[no-]animate', 'generate an image or a video') do |animate| @options.animate = animate end begin opts.parse!(@arguments) @log_files = Dir.glob(@arguments) raise 'no log files given' if @log_files.empty? raise 'invalid log file given' unless @log_files.all?{|file| File.readable? file} process_options rescue puts 'Error: ' + $! return false end true end # Performs post-parse processing on options def process_options $visualization_config = @options end def output_options puts 'Options:' @options.marshal_dump.sort{|a,b| a[0].to_s <=> b[0].to_s}.each do |name, val| puts " #{name} = #{val}" end end # True if required arguments were provided def arguments_valid? video_formats = %w[avi mpg mp4] is_video_format = video_formats.any?{ |video_format| video_format == @options.output_format.downcase } return false if !@options.animate && is_video_format return false if @options.animate && !is_video_format true end def process_arguments # TODO - place in local vars, etc end def output_help puts @opts.help end def output_version puts "#{File.basename(__FILE__)} version #{VERSION}" end def process_command # TODO - do whatever this app does #process_standard_input # [Optional] visualize @log_files end def process_standard_input input = @stdin.read # TODO - process input end end # Create and run the application app = App.new(ARGV, STDIN) app.run diff --git a/lib/ip-world-map/apache_log_visualizer.rb b/lib/ip-world-map/apache_log_visualizer.rb index 17d6269..3d36b20 100644 --- a/lib/ip-world-map/apache_log_visualizer.rb +++ b/lib/ip-world-map/apache_log_visualizer.rb @@ -1,70 +1,68 @@ #coordinates_home = [11.6220338, 48.1276458] # Munich #coordinates_home = [13.4114943, 52.5234802] # Berlin #coordinates_home = [12.3387844, 45.4343363] # Venezia def detect_time_format times some_samples = times.sort[0..99] smallest_period = some_samples.each_cons(2).collect{ |time1, time2| (time1 - time2).abs }.min || 1 return '%b %d %Y %H:%M' if smallest_period < 3600 # scale: minutes return '%b %d %Y %H:00' if smallest_period < 86400 # scale: hours return '%b %d %Y' # scale: days end -def access_image(log_files) +def access_image log_files analyzer = ApacheLogAnalyzer.new(log_files) - analyzer.load_cached_coordinates_from_file details = analyzer.analyze positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } visualization = Visualization.new image = visualization.draw_positions(positions) save_image image end -def access_animation(log_files) +def access_animation log_files analyzer = ApacheLogAnalyzer.new(log_files) - analyzer.load_cached_coordinates_from_file details = analyzer.analyze grouped_details = analyzer.group_by_time(details, $visualization_config.group_seconds) animation = Magick::ImageList.new visualization = Visualization.new time_format = $visualization_config.time_format || detect_time_format(grouped_details.keys) frame_number = 0 grouped_details.sort.each do |time, details| frame_number += 1 visualization.new_frame positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } p [time, details.size, positions.size] image = visualization.draw_positions(positions) InformationDrawer.new.draw_info(image, visualization, time.strftime(time_format)) save_image image, frame_number end create_animation end -def save_image(image, frame_number = 0) +def save_image image, frame_number = 0 if $visualization_config.animate image.write "animation.#{'%09d' % frame_number}.bmp" else image.write "snapshot.#{$visualization_config.output_format}" end end def create_animation success = system "ffmpeg -r #{$visualization_config.frames_per_second} -qscale 1 -y -i animation.%09d.bmp animation.#{$visualization_config.output_format}" raise 'could not create the animation' unless success end -def visualize(log_files) +def visualize log_files if $visualization_config.animate access_animation(log_files) else access_image(log_files) end end diff --git a/lib/ip-world-map/file_utils.rb b/lib/ip-world-map/file_utils.rb index 0dda484..117941f 100644 --- a/lib/ip-world-map/file_utils.rb +++ b/lib/ip-world-map/file_utils.rb @@ -1,16 +1,16 @@ require 'zlib' module FileUtils def self.zipped? filename %w[.gz .Z].include? File.extname(filename) end - def self.open (filename, &block) + def self.open filename, &block if zipped? filename Zlib::GzipReader.open(filename, &block) else File.open(filename, &block) end end end
darxriggs/ip-world-map
1e3932d4f633805b10f48d5a07efec148d634eb9
refactored IP -> locationn lookup into separate class
diff --git a/lib/ip-world-map.rb b/lib/ip-world-map.rb index 2595ea5..31c11c7 100644 --- a/lib/ip-world-map.rb +++ b/lib/ip-world-map.rb @@ -1,15 +1,16 @@ require 'rubygems' require 'RMagick' +require 'ip-world-map/ip_lookup_service' require 'ip-world-map/log_analyzer' require 'ip-world-map/information_drawer' require 'ip-world-map/apache_log_analyzer' require 'ip-world-map/apache_log_visualizer' require 'ip-world-map/decay' require 'ip-world-map/file_utils' require 'ip-world-map/point_in_time' require 'ip-world-map/visualization' require 'ip-world-map/logfile_mock' diff --git a/lib/ip-world-map/ip_lookup_service.rb b/lib/ip-world-map/ip_lookup_service.rb new file mode 100644 index 0000000..3ff2b4a --- /dev/null +++ b/lib/ip-world-map/ip_lookup_service.rb @@ -0,0 +1,52 @@ +require 'net/http' +require 'yaml' + +class IpLookupService + + def initialize filename = nil + @filename = filename || File.join(File.dirname(__FILE__), '..', '..', 'resources', 'coordinates.yml') + reset + load_coordinates + end + + def reset + @host_coordinates = {} + @host_ips = {} + end + + def coordinates_for_host host + unless @host_coordinates[host] + @host_ips[host] ||= ip_for_host(host) + + response = Net::HTTP.get('api.hostip.info', "/get_html.php?position=true&ip=#{@host_ips[host]}") + latitude = response.match(/Latitude: (-?[0-9.]+)/)[1].to_f rescue nil + longitude = response.match(/Longitude: (-?[0-9.]+)/)[1].to_f rescue nil + @host_coordinates[host] = [longitude, latitude] + end + + @host_coordinates[host] + end + + def ip_for_host host + is_ip?(host) ? host : Socket.getaddrinfo(host, nil)[0][3] rescue nil + end + + def is_ip? string + /^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$/.match(string) != nil + end + + def save_coordinates + File.open(@filename, 'w'){ |f| f.write @host_coordinates.to_yaml } + end + + def load_coordinates + @host_coordinates = YAML.load_file(@filename) if File.readable? @filename + end + + def stats + unknown_coordinates, known_coordinates = @host_coordinates.partition{ |ip, coords| coords.include? nil } + + { :unknown_coordinates => unknown_coordinates.size, :known_coordinates => known_coordinates.size } + end +end + diff --git a/lib/ip-world-map/log_analyzer.rb b/lib/ip-world-map/log_analyzer.rb index 7ab5f5d..7b48da8 100644 --- a/lib/ip-world-map/log_analyzer.rb +++ b/lib/ip-world-map/log_analyzer.rb @@ -1,97 +1,55 @@ -require 'time' -require 'date' -require 'net/http' -require 'yaml' - class LogAnalyzer attr_accessor :host_coordinates def initialize *filenames - @COORDINATES_FILE = File.join(File.dirname(__FILE__), '..', '..', 'resources', 'coordinates.yml') @filenames = filenames.flatten.sort.uniq - @host_coordinates = {} - @host_ips = {} - end - - def ip_for_host host - is_ip?(host) ? host : Socket.getaddrinfo(host, nil)[0][3] rescue nil - end - - def is_ip? string - /^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$/.match(string) != nil - end - - def coordinates_for_host host - unless @host_coordinates[host] - @host_ips[host] ||= ip_for_host(host) - - response = Net::HTTP.get('api.hostip.info', "/get_html.php?position=true&ip=#{@host_ips[host]}").split(/\n/) - latitude = response[2].match(/Latitude: (-?[0-9.]+)/)[1].to_f rescue nil - longitude = response[3].match(/Longitude: (-?[0-9.]+)/)[1].to_f rescue nil - @host_coordinates[host] = [longitude, latitude] - end - - @host_coordinates[host] + @ip_lookup_service = IpLookupService.new end def details_from_line line host = extract_host_from_line(line) time = extract_time_from_line(line) - coordinates = coordinates_for_host(host) + coordinates = @ip_lookup_service.coordinates_for_host(host) { :time => time, :host => host, :coordinates => coordinates } end def analyze details = [] @filenames.each do |filename| puts filename FileUtils.open(filename) do |file| lines = file.readlines lines.each do |line| details << details_from_line(line) end end end details end - def save_coordinates_to_file filename = @COORDINATES_FILE - File.open(filename, 'w'){ |f| f.write @host_coordinates.to_yaml } - end - - def load_cached_coordinates_from_file filename = @COORDINATES_FILE - @host_coordinates = YAML.load_file(filename) if File.readable? filename - end - - def stats - unknown_coordinates, known_coordinates = @host_coordinates.partition{ |ip, coords| coords.include? nil } - - { :unknown_coordinates => unknown_coordinates.size, :known_coordinates => known_coordinates.size } - end - def calculate_oldest_time details details.min{ |a, b| a[:time] <=> b[:time] }[:time] end def group_by_time details, slot_in_seconds return {} unless details && slot_in_seconds details_per_slot = {} # TODO: maybe assign empty arrays to missing slots where no traffic was detected details.each do |detail| slot_start_time = calculate_slot_start_time(detail[:time], slot_in_seconds) details_per_slot[slot_start_time] ||= [] details_per_slot[slot_start_time] << detail end details_per_slot end def calculate_slot_start_time time, slot_in_seconds Time.at(time.tv_sec - (time.tv_sec % slot_in_seconds)) end end
darxriggs/ip-world-map
0925f74d0f167f82d47124d9ed1fea07f825e0a0
implemented saving the results as image or video
diff --git a/README.rdoc b/README.rdoc index 2387075..97f8d12 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,68 +1,67 @@ = IP World Map This tool can be used to visualize web access logfiles. It performs geo-location resolution on the IPs and can generate: * a fixed image * an animated image * a video == Installation Install [Gemcutter](http://gemcutter.org) then execute: sudo gem install ip-world-map == Supported platforms Tested with Ruby 1.8.7, 1.9.1 under *nix == Examples The script generates an animated gif with 640x480 and 25fps (default settings). ip-world-map /var/log/apache2/access.log* == Usage ip-world-map [options] logfile1 [logfile2] ... == Options --version Display the version -h, --help Display this help message -v, --verbose Verbose output --map-filename VALUE The image to use as background --resolution VALUE (eg.: 640x480) --fps VALUE Animation frames per second (eg.: 25) --fill-dot-color VALUE (eg.: red, 'rgb(255,0,0)', '#FF0000') --fill-dot-scale VALUE (eg.: 10.0) --fill-dot-opacity VALUE range 0.0-1.0 (eg.: 0.0, 0.5, 1.0) --fill-dot-lifetime VALUE (eg.: 15) --time-slot VALUE real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day) - --image-format VALUE (eg.: png, gif, jpeg) - --video-format VALUE (eg.: avi, mpg, mov) + --output-format VALUE one out of many image formats (eg.: png, jpg, gif) or video formats: avi, mpg, mp4 + --[no-]animate generate an image or a video == TODO -* Implement saving the image/video. At the moment it is only generated in memory and shown via RMagick. * Cache/parallelize IP geo-location lookups. ATTENTION: For many IPs generating an animation can take quite long at the moment due to the used webservice. == Author René Scheibe == License Copyright (C) 2010 René Scheibe <rene.scheibe@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. diff --git a/bin/ip-world-map b/bin/ip-world-map index 9f05054..59df5c2 100755 --- a/bin/ip-world-map +++ b/bin/ip-world-map @@ -1,190 +1,198 @@ #!/usr/bin/env ruby require 'rubygems' require 'optparse' require 'ostruct' require 'date' require 'ip-world-map' class App VERSION = '0.0.1' attr_reader :options def initialize(arguments, stdin) @arguments = arguments @stdin = stdin set_defaults end def run if parsed_arguments? && arguments_valid? puts "Start at #{DateTime.now}\n\n" if @options.verbose output_options if @options.verbose process_arguments process_command puts "\nFinished at #{DateTime.now}" if @options.verbose else output_help exit 1 end end protected def set_defaults @options = OpenStruct.new({ :verbose => false, :quiet => false, :map_filename => File.join(File.dirname(__FILE__), '..' , 'resources', 'maps', 'earthmap-1920x960.tif'), :map_width => 800, :map_height => 400, :frames_per_second => 25, :fill_dot_color => 'red', :fill_dot_scale => 10, :fill_dot_opacity => 1.0, :fill_dot_lifetime => 15, :time_format => nil, :group_seconds => 24 * 1 * 60 * 60, - :image_format => nil, - :video_format => 'gif', + :output_format => 'gif', + :animate => true }) end def parsed_arguments? @opts = opts = OptionParser.new opts.banner = 'Usage: ip-world-map [options] log_file1 [logfile2] ...' opts.on('--version', 'Display the version') do output_version exit 0 end opts.on('-h', '--help', 'Display this help message') do output_help exit 0 end opts.on('-v', '--verbose', 'Verbose output') do @options.verbose = true end opts.on('--map-filename VALUE', 'The image to use as background') do |filename| raise 'invalid map file' unless File.readable? filename @options.map_filename = filename end opts.on('--resolution VALUE', '(eg.: 640x480)') do |resolution| raise 'invalid resolution format' unless resolution =~ /^[0-9]+x[0-9]+$/ width, height = resolution.split('x').collect{|v| v.to_i} @options.map_width = width @options.map_height = height end opts.on('--fps VALUE', 'Animation frames per second (eg.: 25)') do |fps| raise 'invalid fps format' unless fps =~ /^[1-9][0-9]*$/ @options.frames_per_second = fps.to_i end opts.on('--fill-dot-color VALUE', "(eg.: red, 'rgb(255,0,0)', '#FF0000')") do |color| Magick::Pixel.from_color color rescue raise 'invalid color (see help for examples)' @options.fill_dot_color = color end opts.on('--fill-dot-scale VALUE', '(eg.: 10.0)') do |scale| raise 'invalid dot scale' unless scale =~ /^[1-9][0-9]*([.][0-9]*)?$/ @options.fill_dot_scale = scale.to_f end opts.on('--fill-dot-opacity VALUE', 'range 0.0-1.0 (eg.: 0.0, 0.5, 1.0)') do |opacity| raise 'invalid dot opacity' unless opacity =~ /^(0([.][0-9]*)?|1([.]0*)?)$/ @options.fill_dot_opacity = opacity.to_f end opts.on('--fill-dot-lifetime VALUE', '(eg.: 15)') do |lifetime| raise 'invalid dot lifetime' unless lifetime =~ /^[1-9][0-9]*$/ @options.fill_dot_lifetime = lifetime.to_i end opts.on('--time-slot VALUE', 'real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day)') do |slot| raise 'invalid time slot' unless slot =~ /^[1-9][0-9]*(sec|min|hour|day)s?$/ value = slot.scan(/[0-9]+/)[0].to_i unit = slot.scan(/[a-z]+[^s]/)[0] unit2secs = {'sec' => 1, 'min' => 60, 'hour' => 60*60, 'day' => 24*60*60} @options.group_seconds = value * unit2secs[unit] end # TODO # opts.on('--time-format', 'gets auto-detected if not specified') { |v| @options.time_format = v } - opts.on('--image-format VALUE', '(eg.: png, gif, jpeg)') do |format| - # TODO: validation - @options.image_format = format + opts.on('--output-format VALUE', 'one out of many image formats (eg.: png, jpg, gif) or video formats: avi, mpg, mp4') do |format| + # accepted_formats = %w[png gif jpg tif bmp avi mpg mp4] + # raise 'invalid output format' unless accepted_formats.include? format + video_formats = %w[avi mpg mp4] + is_supported = Magick.formats.any?{ |supported_format, properties| supported_format.upcase == format.upcase && properties.include?('w') } + is_supported |= video_formats.any?{ |supported_format| supported_format.upcase == format.upcase } + raise 'invalid output format' unless is_supported + @options.output_format = format end - opts.on('--video-format VALUE', '(eg.: avi, mpg, mov)') do |format| - # TODO: validation - @options.video_format = format + opts.on('--[no-]animate', 'generate an image or a video') do |animate| + @options.animate = animate end begin opts.parse!(@arguments) @log_files = Dir.glob(@arguments) raise 'no log files given' if @log_files.empty? raise 'invalid log file given' unless @log_files.all?{|file| File.readable? file} process_options rescue puts 'Error: ' + $! return false end true end # Performs post-parse processing on options def process_options $visualization_config = @options end def output_options puts 'Options:' @options.marshal_dump.sort{|a,b| a[0].to_s <=> b[0].to_s}.each do |name, val| puts " #{name} = #{val}" end end # True if required arguments were provided def arguments_valid? + video_formats = %w[avi mpg mp4] + is_video_format = video_formats.any?{ |video_format| video_format == @options.output_format.downcase } + return false if !@options.animate && is_video_format + return false if @options.animate && !is_video_format true end def process_arguments # TODO - place in local vars, etc end def output_help puts @opts.help end def output_version puts "#{File.basename(__FILE__)} version #{VERSION}" end def process_command # TODO - do whatever this app does #process_standard_input # [Optional] visualize @log_files end def process_standard_input input = @stdin.read # TODO - process input end end # Create and run the application app = App.new(ARGV, STDIN) app.run diff --git a/lib/ip-world-map/apache_log_visualizer.rb b/lib/ip-world-map/apache_log_visualizer.rb index dd8b5a9..17d6269 100644 --- a/lib/ip-world-map/apache_log_visualizer.rb +++ b/lib/ip-world-map/apache_log_visualizer.rb @@ -1,67 +1,70 @@ #coordinates_home = [11.6220338, 48.1276458] # Munich #coordinates_home = [13.4114943, 52.5234802] # Berlin #coordinates_home = [12.3387844, 45.4343363] # Venezia def detect_time_format times - some_samples = times.sort[0..99] - smallest_period = some_samples.each_cons(2).collect{ |time1, time2| (time1 - time2).abs }.min || 1 + some_samples = times.sort[0..99] + smallest_period = some_samples.each_cons(2).collect{ |time1, time2| (time1 - time2).abs }.min || 1 - return '%b %d %Y %H:%M' if smallest_period < 3600 # scale: minutes - return '%b %d %Y %H:00' if smallest_period < 86400 # scale: hours - return '%b %d %Y' # scale: days -end - -def show_some_random_points - logfile = LogfileMock.new - visualization = Visualization.new - visualization.position_quantization_in_degrees = 5.0 - visualization.draw_positions(logfile.positions) - visualization.display + return '%b %d %Y %H:%M' if smallest_period < 3600 # scale: minutes + return '%b %d %Y %H:00' if smallest_period < 86400 # scale: hours + return '%b %d %Y' # scale: days end def access_image(log_files) - analyzer = ApacheLogAnalyzer.new(log_files) - analyzer.load_cached_coordinates_from_file - details = analyzer.analyze - positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } + analyzer = ApacheLogAnalyzer.new(log_files) + analyzer.load_cached_coordinates_from_file + details = analyzer.analyze + positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } - visualization = Visualization.new - visualization.draw_positions(positions).display + visualization = Visualization.new + image = visualization.draw_positions(positions) + save_image image end def access_animation(log_files) - analyzer = ApacheLogAnalyzer.new(log_files) - analyzer.load_cached_coordinates_from_file - details = analyzer.analyze - grouped_details = analyzer.group_by_time(details, $visualization_config.group_seconds) + analyzer = ApacheLogAnalyzer.new(log_files) + analyzer.load_cached_coordinates_from_file + details = analyzer.analyze + grouped_details = analyzer.group_by_time(details, $visualization_config.group_seconds) - animation = Magick::ImageList.new - visualization = Visualization.new - time_format = $visualization_config.time_format || detect_time_format(grouped_details.keys) + animation = Magick::ImageList.new + visualization = Visualization.new + time_format = $visualization_config.time_format || detect_time_format(grouped_details.keys) + frame_number = 0 - grouped_details.sort.each do |time, details| - visualization.new_frame - positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } - p [time, details.size, positions.size] - image = visualization.draw_positions(positions) + grouped_details.sort.each do |time, details| + frame_number += 1 + visualization.new_frame + positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } + p [time, details.size, positions.size] + image = visualization.draw_positions(positions) - InformationDrawer.new.draw_info(image, visualization, time.strftime(time_format)) - animation << image - end + InformationDrawer.new.draw_info(image, visualization, time.strftime(time_format)) + save_image image, frame_number + end - animation.delay = 1000 / ($visualization_config.frames_per_second * 10) -# animation.each_with_index{ |img, idx| p img; img.write("tng.#{'%03i' % idx}.jpg") } -# animation.write 'tng.gif' - animation.animate + create_animation +end + +def save_image(image, frame_number = 0) + if $visualization_config.animate + image.write "animation.#{'%09d' % frame_number}.bmp" + else + image.write "snapshot.#{$visualization_config.output_format}" + end +end + +def create_animation + success = system "ffmpeg -r #{$visualization_config.frames_per_second} -qscale 1 -y -i animation.%09d.bmp animation.#{$visualization_config.output_format}" + raise 'could not create the animation' unless success end def visualize(log_files) - if $visualization_config.video_format - access_animation(log_files) - elsif $visualization_config.image_format - access_image(log_files) - else - show_some_random_points - end + if $visualization_config.animate + access_animation(log_files) + else + access_image(log_files) + end end
darxriggs/ip-world-map
db815b388b7011601bb22173ddf25cfc6bbb2e9d
renamed method
diff --git a/bin/ip-world-map b/bin/ip-world-map index 6cd4f00..9f05054 100755 --- a/bin/ip-world-map +++ b/bin/ip-world-map @@ -1,190 +1,190 @@ #!/usr/bin/env ruby require 'rubygems' require 'optparse' require 'ostruct' require 'date' require 'ip-world-map' class App VERSION = '0.0.1' attr_reader :options def initialize(arguments, stdin) @arguments = arguments @stdin = stdin set_defaults end def run - if parsed_options? && arguments_valid? + if parsed_arguments? && arguments_valid? puts "Start at #{DateTime.now}\n\n" if @options.verbose output_options if @options.verbose process_arguments process_command puts "\nFinished at #{DateTime.now}" if @options.verbose else output_help exit 1 end end protected def set_defaults @options = OpenStruct.new({ :verbose => false, :quiet => false, :map_filename => File.join(File.dirname(__FILE__), '..' , 'resources', 'maps', 'earthmap-1920x960.tif'), :map_width => 800, :map_height => 400, :frames_per_second => 25, :fill_dot_color => 'red', :fill_dot_scale => 10, :fill_dot_opacity => 1.0, :fill_dot_lifetime => 15, :time_format => nil, :group_seconds => 24 * 1 * 60 * 60, :image_format => nil, :video_format => 'gif', }) end - def parsed_options? + def parsed_arguments? @opts = opts = OptionParser.new opts.banner = 'Usage: ip-world-map [options] log_file1 [logfile2] ...' opts.on('--version', 'Display the version') do output_version exit 0 end opts.on('-h', '--help', 'Display this help message') do output_help exit 0 end opts.on('-v', '--verbose', 'Verbose output') do @options.verbose = true end opts.on('--map-filename VALUE', 'The image to use as background') do |filename| raise 'invalid map file' unless File.readable? filename @options.map_filename = filename end opts.on('--resolution VALUE', '(eg.: 640x480)') do |resolution| raise 'invalid resolution format' unless resolution =~ /^[0-9]+x[0-9]+$/ width, height = resolution.split('x').collect{|v| v.to_i} @options.map_width = width @options.map_height = height end opts.on('--fps VALUE', 'Animation frames per second (eg.: 25)') do |fps| raise 'invalid fps format' unless fps =~ /^[1-9][0-9]*$/ @options.frames_per_second = fps.to_i end opts.on('--fill-dot-color VALUE', "(eg.: red, 'rgb(255,0,0)', '#FF0000')") do |color| Magick::Pixel.from_color color rescue raise 'invalid color (see help for examples)' @options.fill_dot_color = color end opts.on('--fill-dot-scale VALUE', '(eg.: 10.0)') do |scale| raise 'invalid dot scale' unless scale =~ /^[1-9][0-9]*([.][0-9]*)?$/ @options.fill_dot_scale = scale.to_f end opts.on('--fill-dot-opacity VALUE', 'range 0.0-1.0 (eg.: 0.0, 0.5, 1.0)') do |opacity| raise 'invalid dot opacity' unless opacity =~ /^(0([.][0-9]*)?|1([.]0*)?)$/ @options.fill_dot_opacity = opacity.to_f end opts.on('--fill-dot-lifetime VALUE', '(eg.: 15)') do |lifetime| raise 'invalid dot lifetime' unless lifetime =~ /^[1-9][0-9]*$/ @options.fill_dot_lifetime = lifetime.to_i end opts.on('--time-slot VALUE', 'real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day)') do |slot| raise 'invalid time slot' unless slot =~ /^[1-9][0-9]*(sec|min|hour|day)s?$/ value = slot.scan(/[0-9]+/)[0].to_i unit = slot.scan(/[a-z]+[^s]/)[0] unit2secs = {'sec' => 1, 'min' => 60, 'hour' => 60*60, 'day' => 24*60*60} @options.group_seconds = value * unit2secs[unit] end # TODO # opts.on('--time-format', 'gets auto-detected if not specified') { |v| @options.time_format = v } opts.on('--image-format VALUE', '(eg.: png, gif, jpeg)') do |format| # TODO: validation @options.image_format = format end opts.on('--video-format VALUE', '(eg.: avi, mpg, mov)') do |format| # TODO: validation @options.video_format = format end begin opts.parse!(@arguments) @log_files = Dir.glob(@arguments) raise 'no log files given' if @log_files.empty? raise 'invalid log file given' unless @log_files.all?{|file| File.readable? file} process_options rescue puts 'Error: ' + $! return false end true end # Performs post-parse processing on options def process_options $visualization_config = @options end def output_options puts 'Options:' @options.marshal_dump.sort{|a,b| a[0].to_s <=> b[0].to_s}.each do |name, val| puts " #{name} = #{val}" end end # True if required arguments were provided def arguments_valid? true end def process_arguments # TODO - place in local vars, etc end def output_help puts @opts.help end def output_version puts "#{File.basename(__FILE__)} version #{VERSION}" end def process_command # TODO - do whatever this app does #process_standard_input # [Optional] visualize @log_files end def process_standard_input input = @stdin.read # TODO - process input end end # Create and run the application app = App.new(ARGV, STDIN) app.run
darxriggs/ip-world-map
f62693dfa75e047f983224ab7e12ad978e4edc44
maded version in Rakefile and executable consistent
diff --git a/Rakefile b/Rakefile index f8c84d7..e5291e5 100644 --- a/Rakefile +++ b/Rakefile @@ -1,39 +1,39 @@ require 'rubygems' require 'spec/version' require 'spec/rake/spectask' require 'rake/gempackagetask' Spec::Rake::SpecTask.new(:spec) do |t| t.spec_files = FileList['spec/**/*.rb'] t.rcov = false t.rcov_opts = ['--exclude', 'spec'] t.verbose = true end spec = Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.summary = 'A tool to generate images/videos of user locations based on Apache log files.' s.name = 'ip-world-map' - s.version = '0.1' + s.version = '0.0.1' s.requirements << 'RMagick' s.require_path = 'lib' s.bindir = 'bin' s.executables = ['ip-world-map'] s.files = FileList['{lib,spec}/**/*'].to_a + ['Rakefile'] + ['resources/maps/earthmap-1920x960.tif'] s.description = s.summary s.author = 'René Scheibe' s.email = 'rene.scheibe@gmail.com' end Rake::GemPackageTask.new(spec) do |pkg| pkg.need_tar = false end task :install_gem => :package do `sudo gem install pkg/*.gem` end task :default => :install_gem
darxriggs/ip-world-map
24a5271d4db33796c41c51549dbbc5dd323e9ab3
cleaned README
diff --git a/README.rdoc b/README.rdoc index e9808b6..8128ecc 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,67 +1,65 @@ = IP World Map This tool can be used to visualize web access logfiles. It performs geo-location resolution on the IPs and can generate: * a fixed image * an animated image * a video == Installation: Install [Gemcutter](http://gemcutter.org) then execute: $ sudo gem install ip-world-map == Supported platforms: Tested with Ruby 1.8.7, 1.9.1 under *nix == Examples: The script generates an animated gif with 640x480 and 25fps (default settings). $ ip-world-map /var/log/apache2/access.log* == Usage ip-world-map [options] log_file1 [logfile2] ... -For help use: ip-world-map -h - == Options -h, --help Displays help message --version Display the version, then exit -v, --verbose Verbose output --image-format (eg.: png, gif, jpeg) --resolution (eg.: 640x480) --video-format (eg.: avi, mpg, mov) --fps (eg.: 25) --fill-dot-color (eg.: red, 'rgb(255,0,0)', '#FF0000') --fill-dot-scale (eg.: 10.0) --fill-dot-opacity range 0.0-1.0 (eg.: 0.0, 0.5, 1.0) --fill-dot-lifetime (eg.: 15) --time-format gets auto-detected if not specified --time-slot real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day) --image-format (eg.: gif, png, jpg) --video-format (eg.: avi, mpg) == Author René Scheibe == License: Copyright (C) 2010 René Scheibe <rene.scheibe@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
darxriggs/ip-world-map
ad6041443bd444bd5be4f769a3ef50c465dbc0ba
replaced 'Rene' with 'René'
diff --git a/README.rdoc b/README.rdoc index 092fa73..e9808b6 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,67 +1,67 @@ = IP World Map This tool can be used to visualize web access logfiles. It performs geo-location resolution on the IPs and can generate: * a fixed image * an animated image * a video == Installation: Install [Gemcutter](http://gemcutter.org) then execute: $ sudo gem install ip-world-map == Supported platforms: Tested with Ruby 1.8.7, 1.9.1 under *nix == Examples: The script generates an animated gif with 640x480 and 25fps (default settings). $ ip-world-map /var/log/apache2/access.log* == Usage ip-world-map [options] log_file1 [logfile2] ... For help use: ip-world-map -h == Options -h, --help Displays help message --version Display the version, then exit -v, --verbose Verbose output --image-format (eg.: png, gif, jpeg) --resolution (eg.: 640x480) --video-format (eg.: avi, mpg, mov) --fps (eg.: 25) --fill-dot-color (eg.: red, 'rgb(255,0,0)', '#FF0000') --fill-dot-scale (eg.: 10.0) --fill-dot-opacity range 0.0-1.0 (eg.: 0.0, 0.5, 1.0) --fill-dot-lifetime (eg.: 15) --time-format gets auto-detected if not specified --time-slot real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day) --image-format (eg.: gif, png, jpg) --video-format (eg.: avi, mpg) == Author -Rene Scheibe +René Scheibe == License: -Copyright (C) 2010 Rene Scheibe <rene.scheibe@gmail.com> +Copyright (C) 2010 René Scheibe <rene.scheibe@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. diff --git a/Rakefile b/Rakefile index bbf1509..f8c84d7 100644 --- a/Rakefile +++ b/Rakefile @@ -1,39 +1,39 @@ require 'rubygems' require 'spec/version' require 'spec/rake/spectask' require 'rake/gempackagetask' Spec::Rake::SpecTask.new(:spec) do |t| t.spec_files = FileList['spec/**/*.rb'] t.rcov = false t.rcov_opts = ['--exclude', 'spec'] t.verbose = true end spec = Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.summary = 'A tool to generate images/videos of user locations based on Apache log files.' s.name = 'ip-world-map' s.version = '0.1' s.requirements << 'RMagick' s.require_path = 'lib' s.bindir = 'bin' s.executables = ['ip-world-map'] s.files = FileList['{lib,spec}/**/*'].to_a + ['Rakefile'] + ['resources/maps/earthmap-1920x960.tif'] s.description = s.summary - s.author = 'Rene Scheibe' + s.author = 'René Scheibe' s.email = 'rene.scheibe@gmail.com' end Rake::GemPackageTask.new(spec) do |pkg| pkg.need_tar = false end task :install_gem => :package do `sudo gem install pkg/*.gem` end task :default => :install_gem
darxriggs/ip-world-map
7758882bba66111814486fea5505cf7927f3d1d3
refatored executable to use optparse instead of rdoc/usage to print the help message
diff --git a/bin/ip-world-map b/bin/ip-world-map index 6249c25..6cd4f00 100755 --- a/bin/ip-world-map +++ b/bin/ip-world-map @@ -1,218 +1,190 @@ #!/usr/bin/env ruby -# == Synopsis -# This application can be used to visualize web access logfiles. -# It performs geo-location resolution on the IPs and can generate: -# - a fixed image -# - an animated image -# - a video -# -# == Examples -# The script generates an animated gif with 640x480 and 25fps (default settings). -# visualize_access_locations /var/log/apache2/access.log* -# -# == Usage -# visualize_access_locations [options] log_file1 [logfile2] ... -# -# For help use: visualize_access_locations -h -# -# == Options -# -h, --help Displays help message -# --version Display the version, then exit -# -v, --verbose Verbose output -# --image-format (eg.: png, gif, jpeg) -# --resolution (eg.: 640x480) -# --video-format (eg.: avi, mpg, mov) -# --fps (eg.: 25) -# --fill-dot-color (eg.: red, 'rgb(255,0,0)', '#FF0000') -# --fill-dot-scale (eg.: 10.0) -# --fill-dot-opacity range 0.0-1.0 (eg.: 0.0, 0.5, 1.0) -# --fill-dot-lifetime (eg.: 15) -# --time-format gets auto-detected if not specified -# --time-slot real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day) -# --image-format (eg.: gif, png, jpg) -# --video-format (eg.: avi, mpg) -# -# == Author -# René Scheibe -# -# == Copyright -# Copyright (c) 2010 René Scheibe. Licensed under the MIT License: -# http://www.opensource.org/licenses/mit-license.php - require 'rubygems' require 'optparse' require 'ostruct' -require 'rdoc/usage' require 'date' require 'ip-world-map' class App VERSION = '0.0.1' attr_reader :options def initialize(arguments, stdin) @arguments = arguments @stdin = stdin set_defaults end def run if parsed_options? && arguments_valid? puts "Start at #{DateTime.now}\n\n" if @options.verbose output_options if @options.verbose process_arguments process_command puts "\nFinished at #{DateTime.now}" if @options.verbose else - output_usage + output_help + exit 1 end end protected def set_defaults @options = OpenStruct.new({ :verbose => false, :quiet => false, :map_filename => File.join(File.dirname(__FILE__), '..' , 'resources', 'maps', 'earthmap-1920x960.tif'), :map_width => 800, :map_height => 400, :frames_per_second => 25, :fill_dot_color => 'red', :fill_dot_scale => 10, :fill_dot_opacity => 1.0, :fill_dot_lifetime => 15, :time_format => nil, :group_seconds => 24 * 1 * 60 * 60, :image_format => nil, :video_format => 'gif', }) end def parsed_options? - opts = OptionParser.new + @opts = opts = OptionParser.new + + opts.banner = 'Usage: ip-world-map [options] log_file1 [logfile2] ...' + + opts.on('--version', 'Display the version') do + output_version + exit 0 + end - opts.on('--version') { output_version; exit 0 } - opts.on('-h', '--help') { output_help } - opts.on('-v', '--verbose') { @options.verbose = true } + opts.on('-h', '--help', 'Display this help message') do + output_help + exit 0 + end - opts.on('--map-filename VALUE') do |filename| + opts.on('-v', '--verbose', 'Verbose output') do + @options.verbose = true + end + + opts.on('--map-filename VALUE', 'The image to use as background') do |filename| raise 'invalid map file' unless File.readable? filename @options.map_filename = filename end - opts.on('--resolution VALUE') do |resolution| - raise 'invalid resolution format (see help for examples)' unless resolution =~ /^[0-9]+x[0-9]+$/ + opts.on('--resolution VALUE', '(eg.: 640x480)') do |resolution| + raise 'invalid resolution format' unless resolution =~ /^[0-9]+x[0-9]+$/ width, height = resolution.split('x').collect{|v| v.to_i} @options.map_width = width @options.map_height = height end - opts.on('--fps VALUE') do |fps| - raise 'invalid fps format (see help for examples)' unless fps =~ /^[1-9][0-9]*$/ + opts.on('--fps VALUE', 'Animation frames per second (eg.: 25)') do |fps| + raise 'invalid fps format' unless fps =~ /^[1-9][0-9]*$/ @options.frames_per_second = fps.to_i end - opts.on('--fill-dot-color VALUE') do |color| + opts.on('--fill-dot-color VALUE', "(eg.: red, 'rgb(255,0,0)', '#FF0000')") do |color| Magick::Pixel.from_color color rescue raise 'invalid color (see help for examples)' @options.fill_dot_color = color end - opts.on('--fill-dot-scale VALUE') do |scale| - raise 'invalid dot scale (see help for examples)' unless scale =~ /^[1-9][0-9]*([.][0-9]*)?$/ + opts.on('--fill-dot-scale VALUE', '(eg.: 10.0)') do |scale| + raise 'invalid dot scale' unless scale =~ /^[1-9][0-9]*([.][0-9]*)?$/ @options.fill_dot_scale = scale.to_f end - opts.on('--fill-dot-opacity VALUE') do |opacity| - raise 'invalid dot opacity (see help for examples)' unless opacity =~ /^(0([.][0-9]*)?|1([.]0*)?)$/ + opts.on('--fill-dot-opacity VALUE', 'range 0.0-1.0 (eg.: 0.0, 0.5, 1.0)') do |opacity| + raise 'invalid dot opacity' unless opacity =~ /^(0([.][0-9]*)?|1([.]0*)?)$/ @options.fill_dot_opacity = opacity.to_f end - opts.on('--fill-dot-lifetime VALUE') do |lifetime| - raise 'invalid dot lifetime (see help for examples)' unless lifetime =~ /^[1-9][0-9]*$/ + opts.on('--fill-dot-lifetime VALUE', '(eg.: 15)') do |lifetime| + raise 'invalid dot lifetime' unless lifetime =~ /^[1-9][0-9]*$/ @options.fill_dot_lifetime = lifetime.to_i end - opts.on('--time-slot VALUE') do |slot| - raise 'invalid time slot (see help for examples)' unless slot =~ /^[1-9][0-9]*(sec|min|hour|day)s?$/ - value = slot.scan(/[0-9]+/)[0].to_i - unit = slot.scan(/[a-z]+[^s]/)[0] - unit2secs = {'sec' => 1, 'min' => 60, 'hour' => 60*60, 'day' => 24*60*60} - @options.group_seconds = value * unit2secs[unit] + opts.on('--time-slot VALUE', 'real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day)') do |slot| + raise 'invalid time slot' unless slot =~ /^[1-9][0-9]*(sec|min|hour|day)s?$/ + value = slot.scan(/[0-9]+/)[0].to_i + unit = slot.scan(/[a-z]+[^s]/)[0] + unit2secs = {'sec' => 1, 'min' => 60, 'hour' => 60*60, 'day' => 24*60*60} + @options.group_seconds = value * unit2secs[unit] end -# opts.on('--time-format') { |v| @options.time_format = v } + # TODO + # opts.on('--time-format', 'gets auto-detected if not specified') { |v| @options.time_format = v } - opts.on('--image-format VALUE') do |format| - # TODO: validation - @options.image_format = format + opts.on('--image-format VALUE', '(eg.: png, gif, jpeg)') do |format| + # TODO: validation + @options.image_format = format end - opts.on('--video-format VALUE') do |format| - # TODO: validation - @options.video_format = format + opts.on('--video-format VALUE', '(eg.: avi, mpg, mov)') do |format| + # TODO: validation + @options.video_format = format end - opts.parse!(@arguments)# rescue return false - - @log_files = Dir.glob(@arguments) - raise 'no log files given' if @log_files.empty? - raise 'invalid log file given' unless @log_files.all?{|file| File.readable? file} + begin + opts.parse!(@arguments) + @log_files = Dir.glob(@arguments) + raise 'no log files given' if @log_files.empty? + raise 'invalid log file given' unless @log_files.all?{|file| File.readable? file} + process_options + rescue + puts 'Error: ' + $! + return false + end - process_options true end # Performs post-parse processing on options def process_options $visualization_config = @options end def output_options - puts "Options:\n" + puts 'Options:' @options.marshal_dump.sort{|a,b| a[0].to_s <=> b[0].to_s}.each do |name, val| puts " #{name} = #{val}" end end # True if required arguments were provided def arguments_valid? true end def process_arguments - # TO DO - place in local vars, etc + # TODO - place in local vars, etc end def output_help - output_version - RDoc::usage() #exits app - end - - def output_usage - RDoc::usage('usage') # gets usage from comments above + puts @opts.help end def output_version puts "#{File.basename(__FILE__)} version #{VERSION}" end def process_command - # TO DO - do whatever this app does + # TODO - do whatever this app does #process_standard_input # [Optional] visualize @log_files end def process_standard_input input = @stdin.read - # TO DO - process input + # TODO - process input end end # Create and run the application app = App.new(ARGV, STDIN) app.run
darxriggs/ip-world-map
ecf9824898a743c3232a61ce92d7603c0607ea2d
cleaned Rakefile & added email
diff --git a/Rakefile b/Rakefile index f1cac50..bbf1509 100644 --- a/Rakefile +++ b/Rakefile @@ -1,39 +1,39 @@ require 'rubygems' require 'spec/version' require 'spec/rake/spectask' -#require 'cucumber/rake/task' require 'rake/gempackagetask' Spec::Rake::SpecTask.new(:spec) do |t| t.spec_files = FileList['spec/**/*.rb'] t.rcov = false t.rcov_opts = ['--exclude', 'spec'] t.verbose = true end spec = Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.summary = 'A tool to generate images/videos of user locations based on Apache log files.' s.name = 'ip-world-map' s.version = '0.1' s.requirements << 'RMagick' s.require_path = 'lib' s.bindir = 'bin' - s.executables = ['logfile_visualizer'] - s.files = FileList['{lib,spec,features}/**/*'].to_a + + s.executables = ['ip-world-map'] + s.files = FileList['{lib,spec}/**/*'].to_a + ['Rakefile'] + ['resources/maps/earthmap-1920x960.tif'] s.description = s.summary s.author = 'Rene Scheibe' + s.email = 'rene.scheibe@gmail.com' end Rake::GemPackageTask.new(spec) do |pkg| pkg.need_tar = false end task :install_gem => :package do `sudo gem install pkg/*.gem` end task :default => :install_gem
darxriggs/ip-world-map
9b4aa5bc61cb7b49833aa159d88bdf9b934a67d1
extracted drawing the timestamp banner into a separate class
diff --git a/lib/ip-world-map.rb b/lib/ip-world-map.rb index f4e4a4c..2595ea5 100644 --- a/lib/ip-world-map.rb +++ b/lib/ip-world-map.rb @@ -1,14 +1,15 @@ require 'rubygems' require 'RMagick' require 'ip-world-map/log_analyzer' +require 'ip-world-map/information_drawer' require 'ip-world-map/apache_log_analyzer' require 'ip-world-map/apache_log_visualizer' require 'ip-world-map/decay' require 'ip-world-map/file_utils' require 'ip-world-map/point_in_time' require 'ip-world-map/visualization' require 'ip-world-map/logfile_mock' diff --git a/lib/ip-world-map/apache_log_visualizer.rb b/lib/ip-world-map/apache_log_visualizer.rb index 66a9e6c..dd8b5a9 100644 --- a/lib/ip-world-map/apache_log_visualizer.rb +++ b/lib/ip-world-map/apache_log_visualizer.rb @@ -1,90 +1,67 @@ #coordinates_home = [11.6220338, 48.1276458] # Munich #coordinates_home = [13.4114943, 52.5234802] # Berlin #coordinates_home = [12.3387844, 45.4343363] # Venezia -def draw_info_background draw, size - width, height = size[:width], size[:height] - draw.fill('grey') - draw.fill_opacity('50%') - draw.rectangle(0.2 * width, 0.9 * height, 0.8 * width, 0.9 * height + 30) -end - -def draw_info_message draw, size, info - draw.fill('black') - draw.fill_opacity('100%') - draw.text_align(Magick::CenterAlign) - draw.pointsize(20) - draw.text(0.5 * size[:width], 0.9 * size[:height] + 20, info) -end - -def draw_info image, visualization, info - draw = Magick::Draw.new - size = { :width => visualization.map_size[:width], :height => visualization.map_size[:height] } - draw_info_background(draw, size) - draw_info_message(draw, size, info) - draw.draw(image) -end - def detect_time_format times some_samples = times.sort[0..99] smallest_period = some_samples.each_cons(2).collect{ |time1, time2| (time1 - time2).abs }.min || 1 return '%b %d %Y %H:%M' if smallest_period < 3600 # scale: minutes return '%b %d %Y %H:00' if smallest_period < 86400 # scale: hours return '%b %d %Y' # scale: days end def show_some_random_points logfile = LogfileMock.new visualization = Visualization.new visualization.position_quantization_in_degrees = 5.0 visualization.draw_positions(logfile.positions) visualization.display end def access_image(log_files) analyzer = ApacheLogAnalyzer.new(log_files) analyzer.load_cached_coordinates_from_file details = analyzer.analyze positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } visualization = Visualization.new visualization.draw_positions(positions).display end def access_animation(log_files) analyzer = ApacheLogAnalyzer.new(log_files) analyzer.load_cached_coordinates_from_file details = analyzer.analyze grouped_details = analyzer.group_by_time(details, $visualization_config.group_seconds) animation = Magick::ImageList.new visualization = Visualization.new time_format = $visualization_config.time_format || detect_time_format(grouped_details.keys) grouped_details.sort.each do |time, details| visualization.new_frame positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } p [time, details.size, positions.size] image = visualization.draw_positions(positions) - draw_info(image, visualization, time.strftime(time_format)) + InformationDrawer.new.draw_info(image, visualization, time.strftime(time_format)) animation << image end animation.delay = 1000 / ($visualization_config.frames_per_second * 10) # animation.each_with_index{ |img, idx| p img; img.write("tng.#{'%03i' % idx}.jpg") } # animation.write 'tng.gif' animation.animate end def visualize(log_files) if $visualization_config.video_format access_animation(log_files) elsif $visualization_config.image_format access_image(log_files) else show_some_random_points end end diff --git a/lib/ip-world-map/information_drawer.rb b/lib/ip-world-map/information_drawer.rb new file mode 100644 index 0000000..2391d51 --- /dev/null +++ b/lib/ip-world-map/information_drawer.rb @@ -0,0 +1,32 @@ +# Draws the timestamp. +class InformationDrawer + + def initialize + @draw = Magick::Draw.new + end + + def draw_info image, visualization, info + size = { :width => visualization.map_size[:width], :height => visualization.map_size[:height] } + draw_background(size) + draw_message(size, info) + @draw.draw(image) + end + + protected + + def draw_background size + width, height = size[:width], size[:height] + @draw.fill('grey') + @draw.fill_opacity('50%') + @draw.rectangle(0.2 * width, 0.9 * height, 0.8 * width, 0.9 * height + 30) + end + + def draw_message size, info + @draw.fill('black') + @draw.fill_opacity('100%') + @draw.text_align(Magick::CenterAlign) + @draw.pointsize(20) + @draw.text(0.5 * size[:width], 0.9 * size[:height] + 20, info) + end +end +
darxriggs/ip-world-map
09de99724d2bcba64f96529d3d9adaaebebfb017
only ASCII characters in Rakefile
diff --git a/Rakefile b/Rakefile index 323f249..f1cac50 100644 --- a/Rakefile +++ b/Rakefile @@ -1,39 +1,39 @@ require 'rubygems' require 'spec/version' require 'spec/rake/spectask' #require 'cucumber/rake/task' require 'rake/gempackagetask' Spec::Rake::SpecTask.new(:spec) do |t| t.spec_files = FileList['spec/**/*.rb'] t.rcov = false t.rcov_opts = ['--exclude', 'spec'] t.verbose = true end spec = Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.summary = 'A tool to generate images/videos of user locations based on Apache log files.' s.name = 'ip-world-map' s.version = '0.1' s.requirements << 'RMagick' s.require_path = 'lib' s.bindir = 'bin' s.executables = ['logfile_visualizer'] s.files = FileList['{lib,spec,features}/**/*'].to_a + ['Rakefile'] + ['resources/maps/earthmap-1920x960.tif'] s.description = s.summary - s.author = 'René Scheibe' + s.author = 'Rene Scheibe' end Rake::GemPackageTask.new(spec) do |pkg| pkg.need_tar = false end task :install_gem => :package do `sudo gem install pkg/*.gem` end task :default => :install_gem
darxriggs/ip-world-map
8d8b54c2231f07ea6034576182901cefc1557221
added README
diff --git a/README.rdoc b/README.rdoc new file mode 100644 index 0000000..092fa73 --- /dev/null +++ b/README.rdoc @@ -0,0 +1,67 @@ += IP World Map + +This tool can be used to visualize web access logfiles. +It performs geo-location resolution on the IPs and can generate: +* a fixed image +* an animated image +* a video + +== Installation: + +Install [Gemcutter](http://gemcutter.org) then execute: + $ sudo gem install ip-world-map + +== Supported platforms: + +Tested with Ruby 1.8.7, 1.9.1 under *nix + +== Examples: + +The script generates an animated gif with 640x480 and 25fps (default settings). + $ ip-world-map /var/log/apache2/access.log* + +== Usage + +ip-world-map [options] log_file1 [logfile2] ... + +For help use: ip-world-map -h + +== Options + +-h, --help Displays help message + --version Display the version, then exit +-v, --verbose Verbose output + --image-format (eg.: png, gif, jpeg) + --resolution (eg.: 640x480) + --video-format (eg.: avi, mpg, mov) + --fps (eg.: 25) + --fill-dot-color (eg.: red, 'rgb(255,0,0)', '#FF0000') + --fill-dot-scale (eg.: 10.0) + --fill-dot-opacity range 0.0-1.0 (eg.: 0.0, 0.5, 1.0) + --fill-dot-lifetime (eg.: 15) + --time-format gets auto-detected if not specified + --time-slot real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day) + --image-format (eg.: gif, png, jpg) + --video-format (eg.: avi, mpg) + +== Author + +Rene Scheibe + +== License: + +Copyright (C) 2010 Rene Scheibe <rene.scheibe@gmail.com> + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
darxriggs/ip-world-map
3d7e75a18945904fb50934b8209c9f32dc1a1183
added GPLv2 license
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d159169 --- /dev/null +++ b/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License.
darxriggs/ip-world-map
8d2d4897ef4affa7dd1871d662605988ce04106d
made libs non-executable
diff --git a/lib/ip-world-map/apache_log_analyzer.rb b/lib/ip-world-map/apache_log_analyzer.rb old mode 100755 new mode 100644 diff --git a/lib/ip-world-map/apache_log_visualizer.rb b/lib/ip-world-map/apache_log_visualizer.rb old mode 100755 new mode 100644 diff --git a/lib/ip-world-map/decay.rb b/lib/ip-world-map/decay.rb old mode 100755 new mode 100644 diff --git a/lib/ip-world-map/file_utils.rb b/lib/ip-world-map/file_utils.rb old mode 100755 new mode 100644 diff --git a/lib/ip-world-map/log_analyzer.rb b/lib/ip-world-map/log_analyzer.rb old mode 100755 new mode 100644 diff --git a/lib/ip-world-map/logfile_mock.rb b/lib/ip-world-map/logfile_mock.rb old mode 100755 new mode 100644 diff --git a/lib/ip-world-map/point_in_time.rb b/lib/ip-world-map/point_in_time.rb old mode 100755 new mode 100644 diff --git a/lib/ip-world-map/visualization.rb b/lib/ip-world-map/visualization.rb old mode 100755 new mode 100644
darxriggs/ip-world-map
822f2b49e763c801a3f8c780bdb12f3a19a082b1
restructured executable files
diff --git a/Rakefile b/Rakefile index 607eb91..323f249 100644 --- a/Rakefile +++ b/Rakefile @@ -1,39 +1,39 @@ require 'rubygems' require 'spec/version' require 'spec/rake/spectask' #require 'cucumber/rake/task' require 'rake/gempackagetask' Spec::Rake::SpecTask.new(:spec) do |t| t.spec_files = FileList['spec/**/*.rb'] t.rcov = false t.rcov_opts = ['--exclude', 'spec'] t.verbose = true end spec = Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.summary = 'A tool to generate images/videos of user locations based on Apache log files.' s.name = 'ip-world-map' s.version = '0.1' s.requirements << 'RMagick' s.require_path = 'lib' s.bindir = 'bin' - s.executables = ['apache_log_analyzer', 'apache_log_visualizer'] + s.executables = ['logfile_visualizer'] s.files = FileList['{lib,spec,features}/**/*'].to_a + ['Rakefile'] + ['resources/maps/earthmap-1920x960.tif'] s.description = s.summary s.author = 'René Scheibe' end Rake::GemPackageTask.new(spec) do |pkg| pkg.need_tar = false end task :install_gem => :package do `sudo gem install pkg/*.gem` end task :default => :install_gem diff --git a/bin/apache_log_analyzer b/bin/apache_log_analyzer deleted file mode 100755 index 7af8df0..0000000 --- a/bin/apache_log_analyzer +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env ruby - -require 'rubygems' -require 'ip-world-map' - -log_files = Dir.glob(ARGV) -if (log_files.empty?) then puts 'no files given'; exit(1) end - -analyzer = ApacheLogAnalyzer.new(log_files) -analyzer.load_cached_coordinates_from_file - -details = analyzer.analyze -details_per_timeslot = analyzer.group_by_time(details, 24 * 60 * 60) - -p analyzer.stats -p "timeslots: #{details_per_timeslot.size}" -details_per_timeslot.sort().each{ |timeslot, values| p "#{timeslot}: #{values.size} entries" } - diff --git a/bin/run b/bin/logfile_visualizer similarity index 98% rename from bin/run rename to bin/logfile_visualizer index ae04dc6..6249c25 100755 --- a/bin/run +++ b/bin/logfile_visualizer @@ -1,219 +1,218 @@ #!/usr/bin/env ruby # == Synopsis # This application can be used to visualize web access logfiles. # It performs geo-location resolution on the IPs and can generate: # - a fixed image # - an animated image # - a video # # == Examples # The script generates an animated gif with 640x480 and 25fps (default settings). # visualize_access_locations /var/log/apache2/access.log* # # == Usage # visualize_access_locations [options] log_file1 [logfile2] ... # # For help use: visualize_access_locations -h # # == Options # -h, --help Displays help message # --version Display the version, then exit # -v, --verbose Verbose output # --image-format (eg.: png, gif, jpeg) # --resolution (eg.: 640x480) # --video-format (eg.: avi, mpg, mov) # --fps (eg.: 25) # --fill-dot-color (eg.: red, 'rgb(255,0,0)', '#FF0000') # --fill-dot-scale (eg.: 10.0) # --fill-dot-opacity range 0.0-1.0 (eg.: 0.0, 0.5, 1.0) # --fill-dot-lifetime (eg.: 15) # --time-format gets auto-detected if not specified # --time-slot real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day) # --image-format (eg.: gif, png, jpg) # --video-format (eg.: avi, mpg) # # == Author # René Scheibe # # == Copyright # Copyright (c) 2010 René Scheibe. Licensed under the MIT License: # http://www.opensource.org/licenses/mit-license.php require 'rubygems' -require 'RMagick' require 'optparse' -require 'rdoc/usage' require 'ostruct' +require 'rdoc/usage' require 'date' -require File.join(File.dirname(__FILE__), 'apache_log_visualizer') +require 'ip-world-map' class App VERSION = '0.0.1' attr_reader :options def initialize(arguments, stdin) @arguments = arguments @stdin = stdin set_defaults end def run if parsed_options? && arguments_valid? puts "Start at #{DateTime.now}\n\n" if @options.verbose output_options if @options.verbose process_arguments process_command puts "\nFinished at #{DateTime.now}" if @options.verbose else output_usage end end protected def set_defaults @options = OpenStruct.new({ :verbose => false, :quiet => false, :map_filename => File.join(File.dirname(__FILE__), '..' , 'resources', 'maps', 'earthmap-1920x960.tif'), :map_width => 800, :map_height => 400, :frames_per_second => 25, :fill_dot_color => 'red', :fill_dot_scale => 10, :fill_dot_opacity => 1.0, :fill_dot_lifetime => 15, :time_format => nil, :group_seconds => 24 * 1 * 60 * 60, :image_format => nil, :video_format => 'gif', }) end def parsed_options? opts = OptionParser.new opts.on('--version') { output_version; exit 0 } opts.on('-h', '--help') { output_help } opts.on('-v', '--verbose') { @options.verbose = true } opts.on('--map-filename VALUE') do |filename| raise 'invalid map file' unless File.readable? filename @options.map_filename = filename end opts.on('--resolution VALUE') do |resolution| raise 'invalid resolution format (see help for examples)' unless resolution =~ /^[0-9]+x[0-9]+$/ width, height = resolution.split('x').collect{|v| v.to_i} @options.map_width = width @options.map_height = height end opts.on('--fps VALUE') do |fps| raise 'invalid fps format (see help for examples)' unless fps =~ /^[1-9][0-9]*$/ @options.frames_per_second = fps.to_i end opts.on('--fill-dot-color VALUE') do |color| Magick::Pixel.from_color color rescue raise 'invalid color (see help for examples)' @options.fill_dot_color = color end opts.on('--fill-dot-scale VALUE') do |scale| raise 'invalid dot scale (see help for examples)' unless scale =~ /^[1-9][0-9]*([.][0-9]*)?$/ @options.fill_dot_scale = scale.to_f end opts.on('--fill-dot-opacity VALUE') do |opacity| raise 'invalid dot opacity (see help for examples)' unless opacity =~ /^(0([.][0-9]*)?|1([.]0*)?)$/ @options.fill_dot_opacity = opacity.to_f end opts.on('--fill-dot-lifetime VALUE') do |lifetime| raise 'invalid dot lifetime (see help for examples)' unless lifetime =~ /^[1-9][0-9]*$/ @options.fill_dot_lifetime = lifetime.to_i end opts.on('--time-slot VALUE') do |slot| raise 'invalid time slot (see help for examples)' unless slot =~ /^[1-9][0-9]*(sec|min|hour|day)s?$/ value = slot.scan(/[0-9]+/)[0].to_i unit = slot.scan(/[a-z]+[^s]/)[0] unit2secs = {'sec' => 1, 'min' => 60, 'hour' => 60*60, 'day' => 24*60*60} @options.group_seconds = value * unit2secs[unit] end # opts.on('--time-format') { |v| @options.time_format = v } opts.on('--image-format VALUE') do |format| # TODO: validation @options.image_format = format end opts.on('--video-format VALUE') do |format| # TODO: validation @options.video_format = format end opts.parse!(@arguments)# rescue return false @log_files = Dir.glob(@arguments) raise 'no log files given' if @log_files.empty? raise 'invalid log file given' unless @log_files.all?{|file| File.readable? file} process_options true end # Performs post-parse processing on options def process_options $visualization_config = @options end def output_options puts "Options:\n" @options.marshal_dump.sort{|a,b| a[0].to_s <=> b[0].to_s}.each do |name, val| puts " #{name} = #{val}" end end # True if required arguments were provided def arguments_valid? true end def process_arguments # TO DO - place in local vars, etc end def output_help output_version RDoc::usage() #exits app end def output_usage RDoc::usage('usage') # gets usage from comments above end def output_version puts "#{File.basename(__FILE__)} version #{VERSION}" end def process_command # TO DO - do whatever this app does #process_standard_input # [Optional] visualize @log_files end def process_standard_input input = @stdin.read # TO DO - process input end end # Create and run the application app = App.new(ARGV, STDIN) app.run diff --git a/lib/ip-world-map.rb b/lib/ip-world-map.rb index 965fc1d..f4e4a4c 100644 --- a/lib/ip-world-map.rb +++ b/lib/ip-world-map.rb @@ -1,9 +1,14 @@ +require 'rubygems' + +require 'RMagick' + require 'ip-world-map/log_analyzer' require 'ip-world-map/apache_log_analyzer' +require 'ip-world-map/apache_log_visualizer' require 'ip-world-map/decay' require 'ip-world-map/file_utils' require 'ip-world-map/point_in_time' require 'ip-world-map/visualization' require 'ip-world-map/logfile_mock' diff --git a/bin/apache_log_visualizer.rb b/lib/ip-world-map/apache_log_visualizer.rb similarity index 96% rename from bin/apache_log_visualizer.rb rename to lib/ip-world-map/apache_log_visualizer.rb index 58e1b55..66a9e6c 100755 --- a/bin/apache_log_visualizer.rb +++ b/lib/ip-world-map/apache_log_visualizer.rb @@ -1,97 +1,90 @@ -require 'rubygems' -require 'ip-world-map' -require 'ostruct' -require 'RMagick' -require 'optparse' -require 'rdoc/usage' - #coordinates_home = [11.6220338, 48.1276458] # Munich #coordinates_home = [13.4114943, 52.5234802] # Berlin #coordinates_home = [12.3387844, 45.4343363] # Venezia def draw_info_background draw, size width, height = size[:width], size[:height] draw.fill('grey') draw.fill_opacity('50%') draw.rectangle(0.2 * width, 0.9 * height, 0.8 * width, 0.9 * height + 30) end def draw_info_message draw, size, info draw.fill('black') draw.fill_opacity('100%') draw.text_align(Magick::CenterAlign) draw.pointsize(20) draw.text(0.5 * size[:width], 0.9 * size[:height] + 20, info) end def draw_info image, visualization, info draw = Magick::Draw.new size = { :width => visualization.map_size[:width], :height => visualization.map_size[:height] } draw_info_background(draw, size) draw_info_message(draw, size, info) draw.draw(image) end def detect_time_format times some_samples = times.sort[0..99] smallest_period = some_samples.each_cons(2).collect{ |time1, time2| (time1 - time2).abs }.min || 1 return '%b %d %Y %H:%M' if smallest_period < 3600 # scale: minutes return '%b %d %Y %H:00' if smallest_period < 86400 # scale: hours return '%b %d %Y' # scale: days end def show_some_random_points logfile = LogfileMock.new visualization = Visualization.new visualization.position_quantization_in_degrees = 5.0 visualization.draw_positions(logfile.positions) visualization.display end def access_image(log_files) analyzer = ApacheLogAnalyzer.new(log_files) analyzer.load_cached_coordinates_from_file details = analyzer.analyze positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } visualization = Visualization.new visualization.draw_positions(positions).display end def access_animation(log_files) analyzer = ApacheLogAnalyzer.new(log_files) analyzer.load_cached_coordinates_from_file details = analyzer.analyze grouped_details = analyzer.group_by_time(details, $visualization_config.group_seconds) animation = Magick::ImageList.new visualization = Visualization.new time_format = $visualization_config.time_format || detect_time_format(grouped_details.keys) grouped_details.sort.each do |time, details| visualization.new_frame positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } p [time, details.size, positions.size] image = visualization.draw_positions(positions) draw_info(image, visualization, time.strftime(time_format)) animation << image end animation.delay = 1000 / ($visualization_config.frames_per_second * 10) # animation.each_with_index{ |img, idx| p img; img.write("tng.#{'%03i' % idx}.jpg") } # animation.write 'tng.gif' animation.animate end def visualize(log_files) if $visualization_config.video_format access_animation(log_files) elsif $visualization_config.image_format access_image(log_files) else show_some_random_points end end
darxriggs/ip-world-map
25246f889f79ecdb6eb496243e89f314069e640c
removed extra arguments validations (already done during parsing)
diff --git a/bin/run b/bin/run index 36f1276..ae04dc6 100755 --- a/bin/run +++ b/bin/run @@ -1,220 +1,219 @@ #!/usr/bin/env ruby # == Synopsis # This application can be used to visualize web access logfiles. # It performs geo-location resolution on the IPs and can generate: # - a fixed image # - an animated image # - a video # # == Examples # The script generates an animated gif with 640x480 and 25fps (default settings). # visualize_access_locations /var/log/apache2/access.log* # # == Usage # visualize_access_locations [options] log_file1 [logfile2] ... # # For help use: visualize_access_locations -h # # == Options # -h, --help Displays help message # --version Display the version, then exit # -v, --verbose Verbose output # --image-format (eg.: png, gif, jpeg) # --resolution (eg.: 640x480) # --video-format (eg.: avi, mpg, mov) # --fps (eg.: 25) # --fill-dot-color (eg.: red, 'rgb(255,0,0)', '#FF0000') # --fill-dot-scale (eg.: 10.0) # --fill-dot-opacity range 0.0-1.0 (eg.: 0.0, 0.5, 1.0) # --fill-dot-lifetime (eg.: 15) # --time-format gets auto-detected if not specified # --time-slot real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day) # --image-format (eg.: gif, png, jpg) # --video-format (eg.: avi, mpg) # # == Author # René Scheibe # # == Copyright # Copyright (c) 2010 René Scheibe. Licensed under the MIT License: # http://www.opensource.org/licenses/mit-license.php require 'rubygems' require 'RMagick' require 'optparse' require 'rdoc/usage' require 'ostruct' require 'date' require File.join(File.dirname(__FILE__), 'apache_log_visualizer') class App VERSION = '0.0.1' attr_reader :options def initialize(arguments, stdin) @arguments = arguments @stdin = stdin set_defaults end def run if parsed_options? && arguments_valid? puts "Start at #{DateTime.now}\n\n" if @options.verbose output_options if @options.verbose process_arguments process_command puts "\nFinished at #{DateTime.now}" if @options.verbose else output_usage end end protected def set_defaults @options = OpenStruct.new({ :verbose => false, :quiet => false, :map_filename => File.join(File.dirname(__FILE__), '..' , 'resources', 'maps', 'earthmap-1920x960.tif'), :map_width => 800, :map_height => 400, :frames_per_second => 25, :fill_dot_color => 'red', :fill_dot_scale => 10, :fill_dot_opacity => 1.0, :fill_dot_lifetime => 15, :time_format => nil, :group_seconds => 24 * 1 * 60 * 60, :image_format => nil, :video_format => 'gif', }) end def parsed_options? opts = OptionParser.new opts.on('--version') { output_version; exit 0 } opts.on('-h', '--help') { output_help } opts.on('-v', '--verbose') { @options.verbose = true } opts.on('--map-filename VALUE') do |filename| raise 'invalid map file' unless File.readable? filename @options.map_filename = filename end opts.on('--resolution VALUE') do |resolution| raise 'invalid resolution format (see help for examples)' unless resolution =~ /^[0-9]+x[0-9]+$/ width, height = resolution.split('x').collect{|v| v.to_i} @options.map_width = width @options.map_height = height end opts.on('--fps VALUE') do |fps| raise 'invalid fps format (see help for examples)' unless fps =~ /^[1-9][0-9]*$/ @options.frames_per_second = fps.to_i end opts.on('--fill-dot-color VALUE') do |color| Magick::Pixel.from_color color rescue raise 'invalid color (see help for examples)' @options.fill_dot_color = color end opts.on('--fill-dot-scale VALUE') do |scale| raise 'invalid dot scale (see help for examples)' unless scale =~ /^[1-9][0-9]*([.][0-9]*)?$/ @options.fill_dot_scale = scale.to_f end opts.on('--fill-dot-opacity VALUE') do |opacity| raise 'invalid dot opacity (see help for examples)' unless opacity =~ /^(0([.][0-9]*)?|1([.]0*)?)$/ @options.fill_dot_opacity = opacity.to_f end opts.on('--fill-dot-lifetime VALUE') do |lifetime| raise 'invalid dot lifetime (see help for examples)' unless lifetime =~ /^[1-9][0-9]*$/ @options.fill_dot_lifetime = lifetime.to_i end opts.on('--time-slot VALUE') do |slot| raise 'invalid time slot (see help for examples)' unless slot =~ /^[1-9][0-9]*(sec|min|hour|day)s?$/ value = slot.scan(/[0-9]+/)[0].to_i unit = slot.scan(/[a-z]+[^s]/)[0] unit2secs = {'sec' => 1, 'min' => 60, 'hour' => 60*60, 'day' => 24*60*60} @options.group_seconds = value * unit2secs[unit] end # opts.on('--time-format') { |v| @options.time_format = v } opts.on('--image-format VALUE') do |format| # TODO: validation @options.image_format = format end opts.on('--video-format VALUE') do |format| # TODO: validation @options.video_format = format end opts.parse!(@arguments)# rescue return false @log_files = Dir.glob(@arguments) raise 'no log files given' if @log_files.empty? raise 'invalid log file given' unless @log_files.all?{|file| File.readable? file} process_options true end # Performs post-parse processing on options def process_options $visualization_config = @options end def output_options puts "Options:\n" @options.marshal_dump.sort{|a,b| a[0].to_s <=> b[0].to_s}.each do |name, val| puts " #{name} = #{val}" end end # True if required arguments were provided def arguments_valid? - # TO DO - implement your real logic here - true if @arguments.length == 1 + true end def process_arguments # TO DO - place in local vars, etc end def output_help output_version RDoc::usage() #exits app end def output_usage RDoc::usage('usage') # gets usage from comments above end def output_version puts "#{File.basename(__FILE__)} version #{VERSION}" end def process_command # TO DO - do whatever this app does #process_standard_input # [Optional] visualize @log_files end def process_standard_input input = @stdin.read # TO DO - process input end end # Create and run the application app = App.new(ARGV, STDIN) app.run
darxriggs/ip-world-map
16e6b7df00777658d03c947f52c46a6384f527c6
refactored log file parsing
diff --git a/bin/run b/bin/run index 11a0254..36f1276 100755 --- a/bin/run +++ b/bin/run @@ -1,217 +1,220 @@ #!/usr/bin/env ruby # == Synopsis # This application can be used to visualize web access logfiles. # It performs geo-location resolution on the IPs and can generate: # - a fixed image # - an animated image # - a video # # == Examples # The script generates an animated gif with 640x480 and 25fps (default settings). # visualize_access_locations /var/log/apache2/access.log* # # == Usage # visualize_access_locations [options] log_file1 [logfile2] ... # # For help use: visualize_access_locations -h # # == Options # -h, --help Displays help message # --version Display the version, then exit # -v, --verbose Verbose output # --image-format (eg.: png, gif, jpeg) # --resolution (eg.: 640x480) # --video-format (eg.: avi, mpg, mov) # --fps (eg.: 25) # --fill-dot-color (eg.: red, 'rgb(255,0,0)', '#FF0000') # --fill-dot-scale (eg.: 10.0) # --fill-dot-opacity range 0.0-1.0 (eg.: 0.0, 0.5, 1.0) # --fill-dot-lifetime (eg.: 15) # --time-format gets auto-detected if not specified # --time-slot real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day) # --image-format (eg.: gif, png, jpg) # --video-format (eg.: avi, mpg) # # == Author # René Scheibe # # == Copyright # Copyright (c) 2010 René Scheibe. Licensed under the MIT License: # http://www.opensource.org/licenses/mit-license.php require 'rubygems' require 'RMagick' require 'optparse' require 'rdoc/usage' require 'ostruct' require 'date' require File.join(File.dirname(__FILE__), 'apache_log_visualizer') class App VERSION = '0.0.1' attr_reader :options def initialize(arguments, stdin) @arguments = arguments @stdin = stdin set_defaults end def run if parsed_options? && arguments_valid? puts "Start at #{DateTime.now}\n\n" if @options.verbose output_options if @options.verbose process_arguments process_command puts "\nFinished at #{DateTime.now}" if @options.verbose else output_usage end end protected def set_defaults @options = OpenStruct.new({ :verbose => false, :quiet => false, :map_filename => File.join(File.dirname(__FILE__), '..' , 'resources', 'maps', 'earthmap-1920x960.tif'), :map_width => 800, :map_height => 400, :frames_per_second => 25, :fill_dot_color => 'red', :fill_dot_scale => 10, :fill_dot_opacity => 1.0, :fill_dot_lifetime => 15, :time_format => nil, :group_seconds => 24 * 1 * 60 * 60, :image_format => nil, :video_format => 'gif', }) end def parsed_options? opts = OptionParser.new opts.on('--version') { output_version; exit 0 } opts.on('-h', '--help') { output_help } opts.on('-v', '--verbose') { @options.verbose = true } opts.on('--map-filename VALUE') do |filename| raise 'invalid map file' unless File.readable? filename @options.map_filename = filename end opts.on('--resolution VALUE') do |resolution| raise 'invalid resolution format (see help for examples)' unless resolution =~ /^[0-9]+x[0-9]+$/ width, height = resolution.split('x').collect{|v| v.to_i} @options.map_width = width @options.map_height = height end opts.on('--fps VALUE') do |fps| raise 'invalid fps format (see help for examples)' unless fps =~ /^[1-9][0-9]*$/ @options.frames_per_second = fps.to_i end opts.on('--fill-dot-color VALUE') do |color| Magick::Pixel.from_color color rescue raise 'invalid color (see help for examples)' @options.fill_dot_color = color end opts.on('--fill-dot-scale VALUE') do |scale| raise 'invalid dot scale (see help for examples)' unless scale =~ /^[1-9][0-9]*([.][0-9]*)?$/ @options.fill_dot_scale = scale.to_f end opts.on('--fill-dot-opacity VALUE') do |opacity| raise 'invalid dot opacity (see help for examples)' unless opacity =~ /^(0([.][0-9]*)?|1([.]0*)?)$/ @options.fill_dot_opacity = opacity.to_f end opts.on('--fill-dot-lifetime VALUE') do |lifetime| raise 'invalid dot lifetime (see help for examples)' unless lifetime =~ /^[1-9][0-9]*$/ @options.fill_dot_lifetime = lifetime.to_i end opts.on('--time-slot VALUE') do |slot| raise 'invalid time slot (see help for examples)' unless slot =~ /^[1-9][0-9]*(sec|min|hour|day)s?$/ value = slot.scan(/[0-9]+/)[0].to_i unit = slot.scan(/[a-z]+[^s]/)[0] unit2secs = {'sec' => 1, 'min' => 60, 'hour' => 60*60, 'day' => 24*60*60} @options.group_seconds = value * unit2secs[unit] end # opts.on('--time-format') { |v| @options.time_format = v } opts.on('--image-format VALUE') do |format| # TODO: validation @options.image_format = format end opts.on('--video-format VALUE') do |format| # TODO: validation @options.video_format = format end opts.parse!(@arguments)# rescue return false + + @log_files = Dir.glob(@arguments) + raise 'no log files given' if @log_files.empty? + raise 'invalid log file given' unless @log_files.all?{|file| File.readable? file} + process_options true end # Performs post-parse processing on options def process_options $visualization_config = @options end def output_options puts "Options:\n" @options.marshal_dump.sort{|a,b| a[0].to_s <=> b[0].to_s}.each do |name, val| puts " #{name} = #{val}" end end # True if required arguments were provided def arguments_valid? # TO DO - implement your real logic here true if @arguments.length == 1 end def process_arguments # TO DO - place in local vars, etc end def output_help output_version RDoc::usage() #exits app end def output_usage RDoc::usage('usage') # gets usage from comments above end def output_version puts "#{File.basename(__FILE__)} version #{VERSION}" end def process_command # TO DO - do whatever this app does #process_standard_input # [Optional] - log_files = Dir.glob(ARGV) - if (log_files.empty?) then puts 'no files given'; output_help end - visualize log_files + visualize @log_files end def process_standard_input input = @stdin.read # TO DO - process input end end # Create and run the application app = App.new(ARGV, STDIN) app.run
darxriggs/ip-world-map
2b0be37c7411edd779128c0da6d30b1c6fc7e6b8
removed some obsolete code
diff --git a/bin/run b/bin/run index f22f987..11a0254 100755 --- a/bin/run +++ b/bin/run @@ -1,220 +1,217 @@ #!/usr/bin/env ruby # == Synopsis # This application can be used to visualize web access logfiles. # It performs geo-location resolution on the IPs and can generate: # - a fixed image # - an animated image # - a video # # == Examples # The script generates an animated gif with 640x480 and 25fps (default settings). # visualize_access_locations /var/log/apache2/access.log* # # == Usage # visualize_access_locations [options] log_file1 [logfile2] ... # # For help use: visualize_access_locations -h # # == Options # -h, --help Displays help message # --version Display the version, then exit # -v, --verbose Verbose output # --image-format (eg.: png, gif, jpeg) # --resolution (eg.: 640x480) # --video-format (eg.: avi, mpg, mov) # --fps (eg.: 25) # --fill-dot-color (eg.: red, 'rgb(255,0,0)', '#FF0000') # --fill-dot-scale (eg.: 10.0) # --fill-dot-opacity range 0.0-1.0 (eg.: 0.0, 0.5, 1.0) # --fill-dot-lifetime (eg.: 15) # --time-format gets auto-detected if not specified # --time-slot real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day) # --image-format (eg.: gif, png, jpg) # --video-format (eg.: avi, mpg) # # == Author # René Scheibe # # == Copyright # Copyright (c) 2010 René Scheibe. Licensed under the MIT License: # http://www.opensource.org/licenses/mit-license.php require 'rubygems' require 'RMagick' require 'optparse' require 'rdoc/usage' require 'ostruct' require 'date' require File.join(File.dirname(__FILE__), 'apache_log_visualizer') class App VERSION = '0.0.1' attr_reader :options def initialize(arguments, stdin) @arguments = arguments @stdin = stdin set_defaults end def run if parsed_options? && arguments_valid? puts "Start at #{DateTime.now}\n\n" if @options.verbose output_options if @options.verbose process_arguments process_command puts "\nFinished at #{DateTime.now}" if @options.verbose else output_usage end end protected def set_defaults @options = OpenStruct.new({ :verbose => false, :quiet => false, :map_filename => File.join(File.dirname(__FILE__), '..' , 'resources', 'maps', 'earthmap-1920x960.tif'), :map_width => 800, :map_height => 400, :frames_per_second => 25, :fill_dot_color => 'red', :fill_dot_scale => 10, :fill_dot_opacity => 1.0, :fill_dot_lifetime => 15, :time_format => nil, :group_seconds => 24 * 1 * 60 * 60, :image_format => nil, :video_format => 'gif', - :start_time => nil, - :stop_time => nil, }) end def parsed_options? opts = OptionParser.new opts.on('--version') { output_version; exit 0 } opts.on('-h', '--help') { output_help } opts.on('-v', '--verbose') { @options.verbose = true } opts.on('--map-filename VALUE') do |filename| raise 'invalid map file' unless File.readable? filename @options.map_filename = filename end opts.on('--resolution VALUE') do |resolution| raise 'invalid resolution format (see help for examples)' unless resolution =~ /^[0-9]+x[0-9]+$/ width, height = resolution.split('x').collect{|v| v.to_i} @options.map_width = width @options.map_height = height end opts.on('--fps VALUE') do |fps| raise 'invalid fps format (see help for examples)' unless fps =~ /^[1-9][0-9]*$/ @options.frames_per_second = fps.to_i end opts.on('--fill-dot-color VALUE') do |color| Magick::Pixel.from_color color rescue raise 'invalid color (see help for examples)' @options.fill_dot_color = color end opts.on('--fill-dot-scale VALUE') do |scale| raise 'invalid dot scale (see help for examples)' unless scale =~ /^[1-9][0-9]*([.][0-9]*)?$/ @options.fill_dot_scale = scale.to_f end opts.on('--fill-dot-opacity VALUE') do |opacity| raise 'invalid dot opacity (see help for examples)' unless opacity =~ /^(0([.][0-9]*)?|1([.]0*)?)$/ @options.fill_dot_opacity = opacity.to_f end opts.on('--fill-dot-lifetime VALUE') do |lifetime| raise 'invalid dot lifetime (see help for examples)' unless lifetime =~ /^[1-9][0-9]*$/ @options.fill_dot_lifetime = lifetime.to_i end opts.on('--time-slot VALUE') do |slot| raise 'invalid time slot (see help for examples)' unless slot =~ /^[1-9][0-9]*(sec|min|hour|day)s?$/ value = slot.scan(/[0-9]+/)[0].to_i unit = slot.scan(/[a-z]+[^s]/)[0] unit2secs = {'sec' => 1, 'min' => 60, 'hour' => 60*60, 'day' => 24*60*60} @options.group_seconds = value * unit2secs[unit] end # opts.on('--time-format') { |v| @options.time_format = v } opts.on('--image-format VALUE') do |format| # TODO: validation @options.image_format = format end opts.on('--video-format VALUE') do |format| # TODO: validation @options.video_format = format end opts.parse!(@arguments)# rescue return false process_options true end # Performs post-parse processing on options def process_options $visualization_config = @options end def output_options puts "Options:\n" @options.marshal_dump.sort{|a,b| a[0].to_s <=> b[0].to_s}.each do |name, val| puts " #{name} = #{val}" end end # True if required arguments were provided def arguments_valid? # TO DO - implement your real logic here true if @arguments.length == 1 end - # Setup the arguments def process_arguments # TO DO - place in local vars, etc end def output_help output_version RDoc::usage() #exits app end def output_usage RDoc::usage('usage') # gets usage from comments above end def output_version puts "#{File.basename(__FILE__)} version #{VERSION}" end def process_command # TO DO - do whatever this app does #process_standard_input # [Optional] log_files = Dir.glob(ARGV) if (log_files.empty?) then puts 'no files given'; output_help end visualize log_files end def process_standard_input input = @stdin.read # TO DO - process input end end # Create and run the application app = App.new(ARGV, STDIN) app.run
darxriggs/ip-world-map
a121467066af2fcf7030623aba657a7bc78e32c2
implemented command line parsing
diff --git a/bin/apache_log_visualizer b/bin/apache_log_visualizer.rb similarity index 75% rename from bin/apache_log_visualizer rename to bin/apache_log_visualizer.rb index 67ca97f..58e1b55 100755 --- a/bin/apache_log_visualizer +++ b/bin/apache_log_visualizer.rb @@ -1,107 +1,97 @@ -#!/usr/bin/env ruby - require 'rubygems' require 'ip-world-map' require 'ostruct' require 'RMagick' +require 'optparse' +require 'rdoc/usage' #coordinates_home = [11.6220338, 48.1276458] # Munich #coordinates_home = [13.4114943, 52.5234802] # Berlin #coordinates_home = [12.3387844, 45.4343363] # Venezia -$visualization_config = OpenStruct.new({ - :map_filename => File.join(File.dirname(__FILE__), '..' , 'resources', 'maps', 'earthmap-1920x960.tif'), - :map_width => 800, - :map_height => 400, - :group_seconds => 24 * 1 * 60 * 60, - :frames_per_second => 24, - :fill_dot_color => 'red', - :fill_dot_scale => 10, - :fill_dot_opacity => 1.0, - :fill_dot_lifetime => 15, - :time_format => nil, -}) - def draw_info_background draw, size width, height = size[:width], size[:height] draw.fill('grey') draw.fill_opacity('50%') draw.rectangle(0.2 * width, 0.9 * height, 0.8 * width, 0.9 * height + 30) end def draw_info_message draw, size, info draw.fill('black') draw.fill_opacity('100%') draw.text_align(Magick::CenterAlign) draw.pointsize(20) draw.text(0.5 * size[:width], 0.9 * size[:height] + 20, info) end def draw_info image, visualization, info draw = Magick::Draw.new size = { :width => visualization.map_size[:width], :height => visualization.map_size[:height] } draw_info_background(draw, size) draw_info_message(draw, size, info) draw.draw(image) end def detect_time_format times some_samples = times.sort[0..99] - smallest_period = some_samples.each_cons(2).collect{ |time1, time2| (time1 - time2).abs }.min + smallest_period = some_samples.each_cons(2).collect{ |time1, time2| (time1 - time2).abs }.min || 1 return '%b %d %Y %H:%M' if smallest_period < 3600 # scale: minutes return '%b %d %Y %H:00' if smallest_period < 86400 # scale: hours return '%b %d %Y' # scale: days end def show_some_random_points logfile = LogfileMock.new visualization = Visualization.new visualization.position_quantization_in_degrees = 5.0 visualization.draw_positions(logfile.positions) visualization.display end -def access_image - analyzer = ApacheLogAnalyzer.new(Dir.glob(ARGV)) +def access_image(log_files) + analyzer = ApacheLogAnalyzer.new(log_files) analyzer.load_cached_coordinates_from_file details = analyzer.analyze positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } visualization = Visualization.new visualization.draw_positions(positions).display end -def access_animation - analyzer = ApacheLogAnalyzer.new(Dir.glob(ARGV)) +def access_animation(log_files) + analyzer = ApacheLogAnalyzer.new(log_files) analyzer.load_cached_coordinates_from_file details = analyzer.analyze grouped_details = analyzer.group_by_time(details, $visualization_config.group_seconds) animation = Magick::ImageList.new visualization = Visualization.new time_format = $visualization_config.time_format || detect_time_format(grouped_details.keys) - grouped_details.sort().each do |time, details| + grouped_details.sort.each do |time, details| visualization.new_frame positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } p [time, details.size, positions.size] image = visualization.draw_positions(positions) draw_info(image, visualization, time.strftime(time_format)) animation << image end animation.delay = 1000 / ($visualization_config.frames_per_second * 10) # animation.each_with_index{ |img, idx| p img; img.write("tng.#{'%03i' % idx}.jpg") } -# animation.write "tng.gif" +# animation.write 'tng.gif' animation.animate end -log_files = Dir.glob(ARGV) -if (log_files.empty?) then puts 'no files given'; exit(1) end - -#show_some_random_points -#access_image -access_animation +def visualize(log_files) + if $visualization_config.video_format + access_animation(log_files) + elsif $visualization_config.image_format + access_image(log_files) + else + show_some_random_points + end +end diff --git a/bin/run b/bin/run new file mode 100755 index 0000000..f22f987 --- /dev/null +++ b/bin/run @@ -0,0 +1,220 @@ +#!/usr/bin/env ruby + +# == Synopsis +# This application can be used to visualize web access logfiles. +# It performs geo-location resolution on the IPs and can generate: +# - a fixed image +# - an animated image +# - a video +# +# == Examples +# The script generates an animated gif with 640x480 and 25fps (default settings). +# visualize_access_locations /var/log/apache2/access.log* +# +# == Usage +# visualize_access_locations [options] log_file1 [logfile2] ... +# +# For help use: visualize_access_locations -h +# +# == Options +# -h, --help Displays help message +# --version Display the version, then exit +# -v, --verbose Verbose output +# --image-format (eg.: png, gif, jpeg) +# --resolution (eg.: 640x480) +# --video-format (eg.: avi, mpg, mov) +# --fps (eg.: 25) +# --fill-dot-color (eg.: red, 'rgb(255,0,0)', '#FF0000') +# --fill-dot-scale (eg.: 10.0) +# --fill-dot-opacity range 0.0-1.0 (eg.: 0.0, 0.5, 1.0) +# --fill-dot-lifetime (eg.: 15) +# --time-format gets auto-detected if not specified +# --time-slot real life time visualized per video frame (eg.: 10secs, 1min, 99hours, 1day) +# --image-format (eg.: gif, png, jpg) +# --video-format (eg.: avi, mpg) +# +# == Author +# René Scheibe +# +# == Copyright +# Copyright (c) 2010 René Scheibe. Licensed under the MIT License: +# http://www.opensource.org/licenses/mit-license.php + +require 'rubygems' +require 'RMagick' +require 'optparse' +require 'rdoc/usage' +require 'ostruct' +require 'date' +require File.join(File.dirname(__FILE__), 'apache_log_visualizer') + +class App + VERSION = '0.0.1' + + attr_reader :options + + def initialize(arguments, stdin) + @arguments = arguments + @stdin = stdin + + set_defaults + end + + def run + if parsed_options? && arguments_valid? + puts "Start at #{DateTime.now}\n\n" if @options.verbose + output_options if @options.verbose + process_arguments + process_command + puts "\nFinished at #{DateTime.now}" if @options.verbose + else + output_usage + end + end + + protected + + def set_defaults + @options = OpenStruct.new({ + :verbose => false, + :quiet => false, + :map_filename => File.join(File.dirname(__FILE__), '..' , 'resources', 'maps', 'earthmap-1920x960.tif'), + :map_width => 800, + :map_height => 400, + :frames_per_second => 25, + :fill_dot_color => 'red', + :fill_dot_scale => 10, + :fill_dot_opacity => 1.0, + :fill_dot_lifetime => 15, + :time_format => nil, + :group_seconds => 24 * 1 * 60 * 60, + :image_format => nil, + :video_format => 'gif', + :start_time => nil, + :stop_time => nil, + }) + end + + def parsed_options? + opts = OptionParser.new + + opts.on('--version') { output_version; exit 0 } + opts.on('-h', '--help') { output_help } + opts.on('-v', '--verbose') { @options.verbose = true } + + opts.on('--map-filename VALUE') do |filename| + raise 'invalid map file' unless File.readable? filename + @options.map_filename = filename + end + + opts.on('--resolution VALUE') do |resolution| + raise 'invalid resolution format (see help for examples)' unless resolution =~ /^[0-9]+x[0-9]+$/ + width, height = resolution.split('x').collect{|v| v.to_i} + @options.map_width = width + @options.map_height = height + end + + opts.on('--fps VALUE') do |fps| + raise 'invalid fps format (see help for examples)' unless fps =~ /^[1-9][0-9]*$/ + @options.frames_per_second = fps.to_i + end + + opts.on('--fill-dot-color VALUE') do |color| + Magick::Pixel.from_color color rescue raise 'invalid color (see help for examples)' + @options.fill_dot_color = color + end + + opts.on('--fill-dot-scale VALUE') do |scale| + raise 'invalid dot scale (see help for examples)' unless scale =~ /^[1-9][0-9]*([.][0-9]*)?$/ + @options.fill_dot_scale = scale.to_f + end + + opts.on('--fill-dot-opacity VALUE') do |opacity| + raise 'invalid dot opacity (see help for examples)' unless opacity =~ /^(0([.][0-9]*)?|1([.]0*)?)$/ + @options.fill_dot_opacity = opacity.to_f + end + + opts.on('--fill-dot-lifetime VALUE') do |lifetime| + raise 'invalid dot lifetime (see help for examples)' unless lifetime =~ /^[1-9][0-9]*$/ + @options.fill_dot_lifetime = lifetime.to_i + end + + opts.on('--time-slot VALUE') do |slot| + raise 'invalid time slot (see help for examples)' unless slot =~ /^[1-9][0-9]*(sec|min|hour|day)s?$/ + value = slot.scan(/[0-9]+/)[0].to_i + unit = slot.scan(/[a-z]+[^s]/)[0] + unit2secs = {'sec' => 1, 'min' => 60, 'hour' => 60*60, 'day' => 24*60*60} + @options.group_seconds = value * unit2secs[unit] + end + +# opts.on('--time-format') { |v| @options.time_format = v } + + opts.on('--image-format VALUE') do |format| + # TODO: validation + @options.image_format = format + end + + opts.on('--video-format VALUE') do |format| + # TODO: validation + @options.video_format = format + end + + opts.parse!(@arguments)# rescue return false + process_options + true + end + + # Performs post-parse processing on options + def process_options + $visualization_config = @options + end + + def output_options + puts "Options:\n" + @options.marshal_dump.sort{|a,b| a[0].to_s <=> b[0].to_s}.each do |name, val| + puts " #{name} = #{val}" + end + end + + # True if required arguments were provided + def arguments_valid? + # TO DO - implement your real logic here + true if @arguments.length == 1 + end + + # Setup the arguments + def process_arguments + # TO DO - place in local vars, etc + end + + def output_help + output_version + RDoc::usage() #exits app + end + + def output_usage + RDoc::usage('usage') # gets usage from comments above + end + + def output_version + puts "#{File.basename(__FILE__)} version #{VERSION}" + end + + def process_command + # TO DO - do whatever this app does + #process_standard_input # [Optional] + log_files = Dir.glob(ARGV) + if (log_files.empty?) then puts 'no files given'; output_help end + visualize log_files + end + + def process_standard_input + input = @stdin.read + # TO DO - process input + end +end + +# Create and run the application +app = App.new(ARGV, STDIN) +app.run +
darxriggs/ip-world-map
bd9a1bf98ff8fc490e0d7692bbd88ddc73f315ae
made requiring files environment idependent
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 11a7ccf..95aca2f 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,11 +1,11 @@ begin require 'spec' rescue LoadError require 'rubygems' gem 'rspec' require 'spec' end -$:.unshift(File.dirname(__FILE__) + '/../lib') +$:.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'ip-world-map' diff --git a/spec/time_format.rb b/spec/time_format.rb index 0154bd6..94089ec 100644 --- a/spec/time_format.rb +++ b/spec/time_format.rb @@ -1,19 +1,19 @@ -require File.dirname(__FILE__) + '/spec_helper.rb' +require File.join(File.dirname(__FILE__), 'spec_helper.rb') describe TimeFormat do it 'should return a minute based time format for times within an hour' do now = Time.now times = [now, now + 123456789, now + 1] end it 'should return a hour based time format for times within a day' do now = Time.now times = [now, now + 123456789, now + 1] end it 'should return a day based time format for times greater than a day' do now = Time.now times = [now, now + 123456789, now + 1] end end
darxriggs/ip-world-map
fcef270b733efd3e9aa6389ac16270b6831ddb2c
restructored project to be gem conform
diff --git a/.gitignore b/.gitignore index da8cb79..e575c17 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ *.swp -NS2_FILES nbproject +pkg +resources/NS2_FILES diff --git a/Rakefile b/Rakefile index 42d54a0..607eb91 100644 --- a/Rakefile +++ b/Rakefile @@ -1,10 +1,39 @@ require 'rubygems' require 'spec/version' require 'spec/rake/spectask' +#require 'cucumber/rake/task' +require 'rake/gempackagetask' -Spec::Rake::SpecTask.new('specs') do |t| +Spec::Rake::SpecTask.new(:spec) do |t| t.spec_files = FileList['spec/**/*.rb'] t.rcov = false t.rcov_opts = ['--exclude', 'spec'] t.verbose = true end + +spec = Gem::Specification.new do |s| + s.platform = Gem::Platform::RUBY + s.summary = 'A tool to generate images/videos of user locations based on Apache log files.' + s.name = 'ip-world-map' + s.version = '0.1' + s.requirements << 'RMagick' + s.require_path = 'lib' + s.bindir = 'bin' + s.executables = ['apache_log_analyzer', 'apache_log_visualizer'] + s.files = FileList['{lib,spec,features}/**/*'].to_a + + ['Rakefile'] + + ['resources/maps/earthmap-1920x960.tif'] + s.description = s.summary + s.author = 'René Scheibe' +end + +Rake::GemPackageTask.new(spec) do |pkg| + pkg.need_tar = false +end + +task :install_gem => :package do + `sudo gem install pkg/*.gem` +end + +task :default => :install_gem + diff --git a/lib/ip-world-map.rb b/lib/ip-world-map.rb new file mode 100644 index 0000000..965fc1d --- /dev/null +++ b/lib/ip-world-map.rb @@ -0,0 +1,9 @@ +require 'ip-world-map/log_analyzer' +require 'ip-world-map/apache_log_analyzer' +require 'ip-world-map/decay' +require 'ip-world-map/file_utils' +require 'ip-world-map/point_in_time' +require 'ip-world-map/visualization' + +require 'ip-world-map/logfile_mock' + diff --git a/lib/ip-world-map/apache_log_analyzer.rb b/lib/ip-world-map/apache_log_analyzer.rb new file mode 100755 index 0000000..429f8ec --- /dev/null +++ b/lib/ip-world-map/apache_log_analyzer.rb @@ -0,0 +1,25 @@ +require 'time' + +class ApacheLogAnalyzer < LogAnalyzer + def initialize *filenames + super + @@host_regex = /^([\w.-]+)/ + @@time_regex = /\[(\d{2})\/([a-zA-Z]{3})\/(\d{4}):(\d{2}):(\d{2}):(\d{2}) [+-](\d{2})(\d{2})\]/ + end + + def extract_host_from_line line + # IP: "123.1.2.3" or HOSTNAME: "hostname.domain" + host = $1 if line =~ @@host_regex + end + + def extract_time_from_line line + # CLF format: "[dd/MMM/yyyy:hh:mm:ss +-hhmm]" + + # TODO: add timezone information + #dd, mmm, yyyy, hh, mm, ss, tz_hh, tz_mm = $1, $2, $3, $4, $5, $6, $7, $8 if line =~ @@time_regex + #Time.utc(yyyy, mmm, dd, hh.to_i - tz_hh.to_i, mm, ss) + dd, mmm, yyyy, hh, mm, ss = $1, $2, $3, $4, $5, $6 if line =~ @@time_regex + Time.utc(yyyy, mmm, dd, hh, mm, ss) + end +end + diff --git a/lib/ip-world-map/decay.rb b/lib/ip-world-map/decay.rb new file mode 100755 index 0000000..1b7a401 --- /dev/null +++ b/lib/ip-world-map/decay.rb @@ -0,0 +1,12 @@ +# see http://en.wikipedia.org/wiki/Exponential_decay +class Decay + def initialize initial_value, lifetime + @initial_value = initial_value.to_f + @lifetime = lifetime.to_f + end + + def value time + @initial_value * Math::exp(-time / @lifetime) + end +end + diff --git a/lib/ip-world-map/file_utils.rb b/lib/ip-world-map/file_utils.rb new file mode 100755 index 0000000..0dda484 --- /dev/null +++ b/lib/ip-world-map/file_utils.rb @@ -0,0 +1,16 @@ +require 'zlib' + +module FileUtils + def self.zipped? filename + %w[.gz .Z].include? File.extname(filename) + end + + def self.open (filename, &block) + if zipped? filename + Zlib::GzipReader.open(filename, &block) + else + File.open(filename, &block) + end + end +end + diff --git a/lib/apache_log_analyzer.rb b/lib/ip-world-map/log_analyzer.rb similarity index 58% rename from lib/apache_log_analyzer.rb rename to lib/ip-world-map/log_analyzer.rb index b0c639b..7ab5f5d 100755 --- a/lib/apache_log_analyzer.rb +++ b/lib/ip-world-map/log_analyzer.rb @@ -1,154 +1,97 @@ -#!/usr/bin/env ruby - -require 'zlib' require 'time' require 'date' require 'net/http' require 'yaml' -module FileUtils - def self.zipped? filename - %w[.gz .Z].include? File.extname(filename) - end - - def self.open (filename, &block) - if zipped? filename - Zlib::GzipReader.open(filename, &block) - else - File.open(filename, &block) - end - end -end - - class LogAnalyzer attr_accessor :host_coordinates def initialize *filenames + @COORDINATES_FILE = File.join(File.dirname(__FILE__), '..', '..', 'resources', 'coordinates.yml') @filenames = filenames.flatten.sort.uniq @host_coordinates = {} @host_ips = {} end def ip_for_host host is_ip?(host) ? host : Socket.getaddrinfo(host, nil)[0][3] rescue nil end def is_ip? string /^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$/.match(string) != nil end def coordinates_for_host host unless @host_coordinates[host] @host_ips[host] ||= ip_for_host(host) response = Net::HTTP.get('api.hostip.info', "/get_html.php?position=true&ip=#{@host_ips[host]}").split(/\n/) latitude = response[2].match(/Latitude: (-?[0-9.]+)/)[1].to_f rescue nil longitude = response[3].match(/Longitude: (-?[0-9.]+)/)[1].to_f rescue nil @host_coordinates[host] = [longitude, latitude] end @host_coordinates[host] end def details_from_line line host = extract_host_from_line(line) time = extract_time_from_line(line) coordinates = coordinates_for_host(host) { :time => time, :host => host, :coordinates => coordinates } end def analyze details = [] @filenames.each do |filename| puts filename FileUtils.open(filename) do |file| lines = file.readlines lines.each do |line| details << details_from_line(line) end end end details end - def save_coordinates_to_file filename = 'coordinates.yml' + def save_coordinates_to_file filename = @COORDINATES_FILE File.open(filename, 'w'){ |f| f.write @host_coordinates.to_yaml } end - def load_cached_coordinates_from_file filename = 'coordinates.yml' - @host_coordinates = YAML.load_file(filename) + def load_cached_coordinates_from_file filename = @COORDINATES_FILE + @host_coordinates = YAML.load_file(filename) if File.readable? filename end def stats unknown_coordinates, known_coordinates = @host_coordinates.partition{ |ip, coords| coords.include? nil } { :unknown_coordinates => unknown_coordinates.size, :known_coordinates => known_coordinates.size } end def calculate_oldest_time details details.min{ |a, b| a[:time] <=> b[:time] }[:time] end def group_by_time details, slot_in_seconds return {} unless details && slot_in_seconds details_per_slot = {} # TODO: maybe assign empty arrays to missing slots where no traffic was detected details.each do |detail| slot_start_time = calculate_slot_start_time(detail[:time], slot_in_seconds) details_per_slot[slot_start_time] ||= [] details_per_slot[slot_start_time] << detail end details_per_slot end def calculate_slot_start_time time, slot_in_seconds Time.at(time.tv_sec - (time.tv_sec % slot_in_seconds)) end end - -class ApacheLogAnalyzer < LogAnalyzer - def initialize *filenames - super - @@host_regex = /^([\w.-]+)/ - @@time_regex = /\[(\d{2})\/([a-zA-Z]{3})\/(\d{4}):(\d{2}):(\d{2}):(\d{2}) [+-](\d{2})(\d{2})\]/ - end - - def extract_host_from_line line - # IP: "123.1.2.3" or HOSTNAME: "hostname.domain" - host = $1 if line =~ @@host_regex - end - - def extract_time_from_line line - # CLF format: "[dd/MMM/yyyy:hh:mm:ss +-hhmm]" - - # TODO: add timezone information - #dd, mmm, yyyy, hh, mm, ss, tz_hh, tz_mm = $1, $2, $3, $4, $5, $6, $7, $8 if line =~ @@time_regex - #Time.utc(yyyy, mmm, dd, hh.to_i - tz_hh.to_i, mm, ss) - dd, mmm, yyyy, hh, mm, ss = $1, $2, $3, $4, $5, $6 if line =~ @@time_regex - Time.utc(yyyy, mmm, dd, hh, mm, ss) - end -end - - -if $0 == __FILE__ - log_files = Dir.glob(ARGV) - if (log_files.empty?) then puts 'no files given'; exit(1) end - - analyzer = ApacheLogAnalyzer.new(log_files) - analyzer.load_cached_coordinates_from_file - - details = analyzer.analyze - details_per_timeslot = analyzer.group_by_time(details, 24 * 60 * 60) - - p analyzer.stats - p "timeslots: #{details_per_timeslot.size}" - details_per_timeslot.sort().each{ |timeslot, values| p "#{timeslot}: #{values.size} entries" } -end - diff --git a/lib/ip-world-map/logfile_mock.rb b/lib/ip-world-map/logfile_mock.rb new file mode 100755 index 0000000..b5b6f50 --- /dev/null +++ b/lib/ip-world-map/logfile_mock.rb @@ -0,0 +1,18 @@ +class LogfileMock + attr_accessor :min_random_positions, :max_random_positions + + def initialize + @min_random_positions = 5 + @max_random_positions = 50 + end + + def random_longitude_latitude + [ -10 + rand(25) + rand, 40 + rand(15) + rand ] + end + + def positions + amount = @min_random_positions + rand(@max_random_positions - @min_random_positions + 1) + Array.new(amount){ random_longitude_latitude } + end +end + diff --git a/lib/ip-world-map/point_in_time.rb b/lib/ip-world-map/point_in_time.rb new file mode 100755 index 0000000..a09cf82 --- /dev/null +++ b/lib/ip-world-map/point_in_time.rb @@ -0,0 +1,23 @@ +class PointInTime + attr_reader :x, :y + + def initialize x, y, initial_opacity, lifetime + @x, @y = x, y + @time = 0 + @decay = Decay.new(initial_opacity, lifetime) + end + + def opacity_in_time time + @time = time if time + @decay.value(@time) + end + + def opacity + @decay.value(@time) + end + + def age + @time += 1 + end +end + diff --git a/lib/ip-world-map/visualization.rb b/lib/ip-world-map/visualization.rb new file mode 100755 index 0000000..eee54b0 --- /dev/null +++ b/lib/ip-world-map/visualization.rb @@ -0,0 +1,84 @@ +require 'rubygems' +require 'RMagick' + +class Visualization + attr_accessor :position_quantization_in_degrees, :circle_radius + + def initialize + @map_filename = $visualization_config.map_filename + @raw_image = Magick::ImageList.new(@map_filename).first + if $visualization_config.map_width || $visualization_config.map_height + width = $visualization_config.map_width || @raw_image.columns + height = $visualization_config.map_height || @raw_image.rows + @raw_image.resize! width, height + end + new_frame + @position_quantization_in_degrees = 10.0 + @opacity_visibility_threshold = 0.1 + @circle_radius = (map_size[:width] ** 1.25) / (map_size[:width] * $visualization_config.fill_dot_scale).to_f + @points = [] + end + + def map_size + @map_size ||= { :width => @frame.columns, :height => @frame.rows } + end + + def scale + @scale ||= { :x => 360.0 / map_size[:width], :y => 180.0 / map_size[:height] } + end + + def x_y_from_longitude_latitude longitude, latitude + [ (180 + longitude) / scale[:x], (90 - latitude) / scale[:y] ] + end + + def circle_parameters center_x, center_y + [ center_x, center_y, center_x + circle_radius, center_y ] + end + + def quantize_position position + return position if @position_quantization_in_degrees == 0 + position.collect{ |element| element - element.remainder(@position_quantization_in_degrees) } + end + + def quantize_positions positions + positions.collect{ |position| quantize_position(position) } + end + + def select_visible_points points + points.select{ |point| point.opacity >= @opacity_visibility_threshold } + end + + def draw_positions positions_lon_lat + @draw.fill($visualization_config.fill_dot_color) + + new_points = positions_lon_lat.collect do |longitude, latitude| + x, y = x_y_from_longitude_latitude(longitude, latitude) + PointInTime.new(x, y, $visualization_config.fill_dot_opacity, $visualization_config.fill_dot_lifetime) + end + + @points = @points.concat(new_points) + @points = select_visible_points(@points) +# positions = quantize_positions(@positions) + points = @points + + points.each do |point| + @draw.fill_opacity(point.opacity) + @draw.circle(*circle_parameters(point.x, point.y)) + point.age + end + + @draw.draw(@frame) + + @frame + end + + def display + @frame.display + end + + def new_frame + @draw = Magick::Draw.new + @frame = @raw_image.clone + end +end + diff --git a/lib/visualization.rb b/lib/visualization.rb deleted file mode 100755 index 23c48db..0000000 --- a/lib/visualization.rb +++ /dev/null @@ -1,258 +0,0 @@ -#!/usr/bin/env ruby - -require 'rubygems' -require 'ostruct' -require 'RMagick' -require File.dirname(__FILE__) + "/apache_log_analyzer.rb" - -#coordinates_home = [11.6220338, 48.1276458] # Munich -#coordinates_home = [13.4114943, 52.5234802] # Berlin -#coordinates_home = [12.3387844, 45.4343363] # Venezia - -$visualization_config = OpenStruct.new({ - :map_filename => File.dirname(__FILE__) + "/../maps/earthmap-1920x960.tif", - :map_width => 800, - :map_height => 400, - :group_seconds => 24 * 1 * 60 * 60, - :frames_per_second => 24, - :fill_dot_color => 'red', - :fill_dot_scale => 10, - :fill_dot_opacity => 1.0, - :fill_dot_lifetime => 15, - :time_format => nil, -}) - -############################################################################### - -class LogfileMock - attr_accessor :min_random_positions, :max_random_positions - - def initialize - @min_random_positions = 5 - @max_random_positions = 50 - end - - def random_longitude_latitude - [ -10 + rand(25) + rand, 40 + rand(15) + rand ] - end - - def random_positions - amount = @min_random_positions + rand(@max_random_positions - @min_random_positions + 1) - Array.new(amount) { random_longitude_latitude } - end - alias :positions :random_positions -end - -############################################################################### - -class Visualization - attr_accessor :position_quantization_in_degrees, :circle_radius - - def initialize - @map_filename = $visualization_config.map_filename - @raw_image = Magick::ImageList.new(@map_filename).first - if $visualization_config.map_width || $visualization_config.map_height - width = $visualization_config.map_width || @raw_image.columns - height = $visualization_config.map_height || @raw_image.rows - @raw_image.resize! width, height - end - new_frame - @position_quantization_in_degrees = 10.0 - @opacity_visibility_threshold = 0.1 - @circle_radius = (map_size[:width] ** 1.25) / (map_size[:width] * $visualization_config.fill_dot_scale).to_f - @points = [] - end - - def map_size - @map_size ||= { :width => @frame.columns, :height => @frame.rows } - end - - def scale - @scale ||= { :x => 360.0 / map_size[:width], :y => 180.0 / map_size[:height] } - end - - def x_y_from_longitude_latitude longitude, latitude - [ (180 + longitude) / scale[:x], (90 - latitude) / scale[:y] ] - end - - def circle_parameters center_x, center_y - [ center_x, center_y, center_x + circle_radius, center_y ] - end - - def quantize_position position - return position if @position_quantization_in_degrees == 0 - position.collect{ |element| element - element.remainder(@position_quantization_in_degrees) } - end - - def quantize_positions positions - positions.collect{ |position| quantize_position(position) } - end - - def select_visible_points points - points.select{ |point| point.opacity >= @opacity_visibility_threshold } - end - - def draw_positions positions_lon_lat - @draw.fill($visualization_config.fill_dot_color) - - new_points = positions_lon_lat.collect do |longitude, latitude| - x, y = x_y_from_longitude_latitude(longitude, latitude) - PointInTime.new(x, y, $visualization_config.fill_dot_opacity, $visualization_config.fill_dot_lifetime) - end - - @points = @points.concat(new_points) - @points = select_visible_points(@points) -# positions = quantize_positions(@positions) - points = @points - - points.each do |point| - @draw.fill_opacity(point.opacity) - @draw.circle(*circle_parameters(point.x, point.y)) - point.age - end - - @draw.draw(@frame) - - @frame - end - - def display - @frame.display - end - - def new_frame - @draw = Magick::Draw.new - @frame = @raw_image.clone - end -end - -############################################################################### - -# see http://en.wikipedia.org/wiki/Exponential_decay -class Decay - def initialize initial_value, lifetime - @initial_value = initial_value.to_f - @lifetime = lifetime.to_f - end - - def value time - @initial_value * Math::exp(-time / @lifetime) - end -end - -############################################################################### - -class PointInTime - attr_reader :x, :y - - def initialize x, y, initial_opacity, lifetime - @x, @y = x, y - @time = 0 - @decay = Decay.new(initial_opacity, lifetime) - end - - def opacity_in_time time - @time = time if time - @decay.value(@time) - end - - def opacity - @decay.value(@time) - end - - def age - @time += 1 - end -end - -############################################################################### - -#decay = Decay.new(10, 5) -#p (0..20).collect{ |t| decay.value(t) } -#exit - -#decay = Decay.new(10, 5) -#point = PointInTime.new(0,0, 10,5) -#p (0..20).collect{ |t| point.opacity } -#exit - -def draw_info_background draw, size - width, height = size[:width], size[:height] - draw.fill('grey') - draw.fill_opacity('50%') - draw.rectangle(0.2 * width, 0.9 * height, 0.8 * width, 0.9 * height + 30) -end - -def draw_info_message draw, size, info - draw.fill('black') - draw.fill_opacity('100%') - draw.text_align(Magick::CenterAlign) - draw.pointsize(20) - draw.text(0.5 * size[:width], 0.9 * size[:height] + 20, info) -end - -def draw_info image, visualization, info - draw = Magick::Draw.new - size = { :width => visualization.map_size[:width], :height => visualization.map_size[:height] } - draw_info_background(draw, size) - draw_info_message(draw, size, info) - draw.draw(image) -end - -def detect_time_format times - some_samples = times.sort[0..99] - smallest_period = some_samples.each_cons(2).collect{ |time1, time2| (time1 - time2).abs }.min - - return '%b %d %Y %H:%M' if smallest_period < 3600 # scale: minutes - return '%b %d %Y %H:00' if smallest_period < 86400 # scale: hours - return '%b %d %Y' # scale: days -end - -def show_some_random_points - logfile = LogfileMock.new - visualization = Visualization.new - visualization.position_quantization_in_degrees = 5.0 - visualization.draw_positions(logfile.positions) - visualization.display -end - -def access_image - analyzer = ApacheLogAnalyzer.new(Dir.glob(ARGV)) - analyzer.load_cached_coordinates_from_file - details = analyzer.analyze - positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } - - visualization = Visualization.new - visualization.draw_positions(positions).display -end - -def access_animation - analyzer = ApacheLogAnalyzer.new(Dir.glob(ARGV)) - analyzer.load_cached_coordinates_from_file - details = analyzer.analyze - grouped_details = analyzer.group_by_time(details, $visualization_config.group_seconds) - - animation = Magick::ImageList.new - visualization = Visualization.new - time_format = $visualization_config.time_format || detect_time_format(grouped_details.keys) - - grouped_details.sort().each do |time, details| - visualization.new_frame - positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } - p [time, details.size, positions.size] - image = visualization.draw_positions(positions) - - draw_info(image, visualization, time.strftime(time_format)) - animation << image - end - - animation.delay = 1000 / ($visualization_config.frames_per_second * 10) -# animation.each_with_index{ |img, idx| p img; img.write("tng.#{'%03i' % idx}.jpg") } -# animation.write "tng.gif" - animation.animate -end - -#show_some_random_points -#access_image -access_animation - diff --git a/maps/earthmap-10800x5400.jpg b/resources/maps/earthmap-10800x5400.jpg similarity index 100% rename from maps/earthmap-10800x5400.jpg rename to resources/maps/earthmap-10800x5400.jpg diff --git a/maps/earthmap-1600x800.tif b/resources/maps/earthmap-1600x800.tif similarity index 100% rename from maps/earthmap-1600x800.tif rename to resources/maps/earthmap-1600x800.tif diff --git a/maps/earthmap-1920x960.tif b/resources/maps/earthmap-1920x960.tif similarity index 100% rename from maps/earthmap-1920x960.tif rename to resources/maps/earthmap-1920x960.tif diff --git a/maps/earthmap-800x400.tif b/resources/maps/earthmap-800x400.tif similarity index 100% rename from maps/earthmap-800x400.tif rename to resources/maps/earthmap-800x400.tif diff --git a/maps/earthmap-8192x4096.tif b/resources/maps/earthmap-8192x4096.tif similarity index 100% rename from maps/earthmap-8192x4096.tif rename to resources/maps/earthmap-8192x4096.tif diff --git a/maps/earthmap.readme b/resources/maps/earthmap.readme similarity index 100% rename from maps/earthmap.readme rename to resources/maps/earthmap.readme diff --git a/spec/decay.rb b/spec/decay.rb index 7b98f74..afa54ca 100644 --- a/spec/decay.rb +++ b/spec/decay.rb @@ -1,17 +1,18 @@ require File.dirname(__FILE__) + '/spec_helper.rb' describe PointInTime do it 'should be initialized with either Integers and/or Floats' do Decay.new(10, 5 ) Decay.new(10, 5.0) Decay.new(10.0, 5 ) Decay.new(10.0, 5.0) end it 'should return a value depending on the time' do decay = Decay.new(10, 5) decay.value(0).should be 10 decay.value(2).should be 0 # todo end end + diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 6787f9a..11a7ccf 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,12 +1,11 @@ begin require 'spec' rescue LoadError require 'rubygems' gem 'rspec' require 'spec' end $:.unshift(File.dirname(__FILE__) + '/../lib') +require 'ip-world-map' -require 'apache_log_analyzer' -require 'visualization' diff --git a/spec/time_format.rb b/spec/time_format.rb new file mode 100644 index 0000000..0154bd6 --- /dev/null +++ b/spec/time_format.rb @@ -0,0 +1,19 @@ +require File.dirname(__FILE__) + '/spec_helper.rb' + +describe TimeFormat do + it 'should return a minute based time format for times within an hour' do + now = Time.now + times = [now, now + 123456789, now + 1] + end + + it 'should return a hour based time format for times within a day' do + now = Time.now + times = [now, now + 123456789, now + 1] + end + + it 'should return a day based time format for times greater than a day' do + now = Time.now + times = [now, now + 123456789, now + 1] + end +end +
darxriggs/ip-world-map
02f64ddbe4383bfcd65ad35da880e71c1c5b545a
add bin folder with executables log analyze and visualize Apache log files
diff --git a/bin/apache_log_analyzer b/bin/apache_log_analyzer new file mode 100755 index 0000000..7af8df0 --- /dev/null +++ b/bin/apache_log_analyzer @@ -0,0 +1,18 @@ +#!/usr/bin/env ruby + +require 'rubygems' +require 'ip-world-map' + +log_files = Dir.glob(ARGV) +if (log_files.empty?) then puts 'no files given'; exit(1) end + +analyzer = ApacheLogAnalyzer.new(log_files) +analyzer.load_cached_coordinates_from_file + +details = analyzer.analyze +details_per_timeslot = analyzer.group_by_time(details, 24 * 60 * 60) + +p analyzer.stats +p "timeslots: #{details_per_timeslot.size}" +details_per_timeslot.sort().each{ |timeslot, values| p "#{timeslot}: #{values.size} entries" } + diff --git a/bin/apache_log_visualizer b/bin/apache_log_visualizer new file mode 100755 index 0000000..67ca97f --- /dev/null +++ b/bin/apache_log_visualizer @@ -0,0 +1,107 @@ +#!/usr/bin/env ruby + +require 'rubygems' +require 'ip-world-map' +require 'ostruct' +require 'RMagick' + +#coordinates_home = [11.6220338, 48.1276458] # Munich +#coordinates_home = [13.4114943, 52.5234802] # Berlin +#coordinates_home = [12.3387844, 45.4343363] # Venezia + +$visualization_config = OpenStruct.new({ + :map_filename => File.join(File.dirname(__FILE__), '..' , 'resources', 'maps', 'earthmap-1920x960.tif'), + :map_width => 800, + :map_height => 400, + :group_seconds => 24 * 1 * 60 * 60, + :frames_per_second => 24, + :fill_dot_color => 'red', + :fill_dot_scale => 10, + :fill_dot_opacity => 1.0, + :fill_dot_lifetime => 15, + :time_format => nil, +}) + +def draw_info_background draw, size + width, height = size[:width], size[:height] + draw.fill('grey') + draw.fill_opacity('50%') + draw.rectangle(0.2 * width, 0.9 * height, 0.8 * width, 0.9 * height + 30) +end + +def draw_info_message draw, size, info + draw.fill('black') + draw.fill_opacity('100%') + draw.text_align(Magick::CenterAlign) + draw.pointsize(20) + draw.text(0.5 * size[:width], 0.9 * size[:height] + 20, info) +end + +def draw_info image, visualization, info + draw = Magick::Draw.new + size = { :width => visualization.map_size[:width], :height => visualization.map_size[:height] } + draw_info_background(draw, size) + draw_info_message(draw, size, info) + draw.draw(image) +end + +def detect_time_format times + some_samples = times.sort[0..99] + smallest_period = some_samples.each_cons(2).collect{ |time1, time2| (time1 - time2).abs }.min + + return '%b %d %Y %H:%M' if smallest_period < 3600 # scale: minutes + return '%b %d %Y %H:00' if smallest_period < 86400 # scale: hours + return '%b %d %Y' # scale: days +end + +def show_some_random_points + logfile = LogfileMock.new + visualization = Visualization.new + visualization.position_quantization_in_degrees = 5.0 + visualization.draw_positions(logfile.positions) + visualization.display +end + +def access_image + analyzer = ApacheLogAnalyzer.new(Dir.glob(ARGV)) + analyzer.load_cached_coordinates_from_file + details = analyzer.analyze + positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } + + visualization = Visualization.new + visualization.draw_positions(positions).display +end + +def access_animation + analyzer = ApacheLogAnalyzer.new(Dir.glob(ARGV)) + analyzer.load_cached_coordinates_from_file + details = analyzer.analyze + grouped_details = analyzer.group_by_time(details, $visualization_config.group_seconds) + + animation = Magick::ImageList.new + visualization = Visualization.new + time_format = $visualization_config.time_format || detect_time_format(grouped_details.keys) + + grouped_details.sort().each do |time, details| + visualization.new_frame + positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } + p [time, details.size, positions.size] + image = visualization.draw_positions(positions) + + draw_info(image, visualization, time.strftime(time_format)) + animation << image + end + + animation.delay = 1000 / ($visualization_config.frames_per_second * 10) +# animation.each_with_index{ |img, idx| p img; img.write("tng.#{'%03i' % idx}.jpg") } +# animation.write "tng.gif" + animation.animate +end + +log_files = Dir.glob(ARGV) +if (log_files.empty?) then puts 'no files given'; exit(1) end + +#show_some_random_points +#access_image +access_animation +
darxriggs/ip-world-map
5467d1a3d1341644c1cc51474b4fa7acdd7eb461
added very old uncommited changes
diff --git a/lib/apache_log_analyzer.rb b/lib/apache_log_analyzer.rb index 3d6c424..b0c639b 100755 --- a/lib/apache_log_analyzer.rb +++ b/lib/apache_log_analyzer.rb @@ -1,159 +1,154 @@ #!/usr/bin/env ruby require 'zlib' require 'time' require 'date' require 'net/http' require 'yaml' module FileUtils def self.zipped? filename %w[.gz .Z].include? File.extname(filename) end def self.open (filename, &block) if zipped? filename Zlib::GzipReader.open(filename, &block) else File.open(filename, &block) end end end class LogAnalyzer attr_accessor :host_coordinates def initialize *filenames @filenames = filenames.flatten.sort.uniq @host_coordinates = {} @host_ips = {} end def ip_for_host host is_ip?(host) ? host : Socket.getaddrinfo(host, nil)[0][3] rescue nil end def is_ip? string /^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$/.match(string) != nil end def coordinates_for_host host unless @host_coordinates[host] @host_ips[host] ||= ip_for_host(host) response = Net::HTTP.get('api.hostip.info', "/get_html.php?position=true&ip=#{@host_ips[host]}").split(/\n/) latitude = response[2].match(/Latitude: (-?[0-9.]+)/)[1].to_f rescue nil longitude = response[3].match(/Longitude: (-?[0-9.]+)/)[1].to_f rescue nil @host_coordinates[host] = [longitude, latitude] end @host_coordinates[host] end def details_from_line line host = extract_host_from_line(line) time = extract_time_from_line(line) coordinates = coordinates_for_host(host) { :time => time, :host => host, :coordinates => coordinates } end def analyze details = [] @filenames.each do |filename| puts filename FileUtils.open(filename) do |file| lines = file.readlines lines.each do |line| details << details_from_line(line) end end end details end def save_coordinates_to_file filename = 'coordinates.yml' File.open(filename, 'w'){ |f| f.write @host_coordinates.to_yaml } end - def load_coordinates_from_file filename = 'coordinates.yml' + def load_cached_coordinates_from_file filename = 'coordinates.yml' @host_coordinates = YAML.load_file(filename) end def stats unknown_coordinates, known_coordinates = @host_coordinates.partition{ |ip, coords| coords.include? nil } { :unknown_coordinates => unknown_coordinates.size, :known_coordinates => known_coordinates.size } end + def calculate_oldest_time details + details.min{ |a, b| a[:time] <=> b[:time] }[:time] + end + def group_by_time details, slot_in_seconds - latest_time = details.min{ |a,b| a[:time] <=> b[:time] }[:time] - slot_time = slot_start_time(latest_time, slot_in_seconds) + return {} unless details && slot_in_seconds details_per_slot = {} - # quite slow algorithm -# while details.count > 0 do -# slot_cap_time = slot_time + slot_in_seconds -# details_in_slot, details = details.partition{ |data| data[:time] < slot_cap_time } -# details_per_slot[slot_time] = details_in_slot -# slot_time = slot_cap_time -# end - # TODO: maybe assign empty arrays to missing slots where no traffic was detected - details.each do |data| - time = slot_start_time(data[:time], slot_in_seconds) - details_per_slot[time] = [] unless details_per_slot[time] - details_per_slot[time] << data + details.each do |detail| + slot_start_time = calculate_slot_start_time(detail[:time], slot_in_seconds) + details_per_slot[slot_start_time] ||= [] + details_per_slot[slot_start_time] << detail end details_per_slot end - def slot_start_time time, slot_in_seconds + def calculate_slot_start_time time, slot_in_seconds Time.at(time.tv_sec - (time.tv_sec % slot_in_seconds)) end end class ApacheLogAnalyzer < LogAnalyzer def initialize *filenames super @@host_regex = /^([\w.-]+)/ @@time_regex = /\[(\d{2})\/([a-zA-Z]{3})\/(\d{4}):(\d{2}):(\d{2}):(\d{2}) [+-](\d{2})(\d{2})\]/ end def extract_host_from_line line # IP: "123.1.2.3" or HOSTNAME: "hostname.domain" host = $1 if line =~ @@host_regex end def extract_time_from_line line - # CLF format: "[dd/MMM/yyyy:hh:mm:ss +-hhmm]" => parsable format: "dd/MMM/yyyy hh:mm:ss +-hhmm" + # CLF format: "[dd/MMM/yyyy:hh:mm:ss +-hhmm]" - # 1. quite slow - # time_string = line.scan(/\[[\w\/:+ ]+\]/).first[1...-1].sub(':', ' ') - # Time.parse(time_string) - - # 2. TODO: add timezone information + # TODO: add timezone information #dd, mmm, yyyy, hh, mm, ss, tz_hh, tz_mm = $1, $2, $3, $4, $5, $6, $7, $8 if line =~ @@time_regex #Time.utc(yyyy, mmm, dd, hh.to_i - tz_hh.to_i, mm, ss) dd, mmm, yyyy, hh, mm, ss = $1, $2, $3, $4, $5, $6 if line =~ @@time_regex Time.utc(yyyy, mmm, dd, hh, mm, ss) end end if $0 == __FILE__ - analyzer = ApacheLogAnalyzer.new(Dir.glob(ARGV)) - analyzer.load_coordinates_from_file + log_files = Dir.glob(ARGV) + if (log_files.empty?) then puts 'no files given'; exit(1) end + + analyzer = ApacheLogAnalyzer.new(log_files) + analyzer.load_cached_coordinates_from_file details = analyzer.analyze - details_per_slot = analyzer.group_by_time(details, 24 * 60 * 60) + details_per_timeslot = analyzer.group_by_time(details, 24 * 60 * 60) p analyzer.stats - details_per_slot.sort().each{ |slot, values| p "#{slot}: #{values.size}" } - p details_per_slot.size + p "timeslots: #{details_per_timeslot.size}" + details_per_timeslot.sort().each{ |timeslot, values| p "#{timeslot}: #{values.size} entries" } end + diff --git a/lib/visualization.rb b/lib/visualization.rb index d13fbf4..23c48db 100755 --- a/lib/visualization.rb +++ b/lib/visualization.rb @@ -1,223 +1,258 @@ #!/usr/bin/env ruby require 'rubygems' +require 'ostruct' require 'RMagick' require File.dirname(__FILE__) + "/apache_log_analyzer.rb" #coordinates_home = [11.6220338, 48.1276458] # Munich #coordinates_home = [13.4114943, 52.5234802] # Berlin #coordinates_home = [12.3387844, 45.4343363] # Venezia -############################################################################### - -class Logfile - def initialize filename - end -end +$visualization_config = OpenStruct.new({ + :map_filename => File.dirname(__FILE__) + "/../maps/earthmap-1920x960.tif", + :map_width => 800, + :map_height => 400, + :group_seconds => 24 * 1 * 60 * 60, + :frames_per_second => 24, + :fill_dot_color => 'red', + :fill_dot_scale => 10, + :fill_dot_opacity => 1.0, + :fill_dot_lifetime => 15, + :time_format => nil, +}) ############################################################################### class LogfileMock attr_accessor :min_random_positions, :max_random_positions def initialize @min_random_positions = 5 @max_random_positions = 50 end def random_longitude_latitude [ -10 + rand(25) + rand, 40 + rand(15) + rand ] end def random_positions amount = @min_random_positions + rand(@max_random_positions - @min_random_positions + 1) Array.new(amount) { random_longitude_latitude } end alias :positions :random_positions end ############################################################################### class Visualization attr_accessor :position_quantization_in_degrees, :circle_radius - #def initialize filename = File.dirname(__FILE__) + "/../maps/earthmap-1920x960.tif" - def initialize filename = File.dirname(__FILE__) + "/../maps/earthmap-800x400.tif" - @map_filename = filename - @draw = Magick::Draw.new - @image = Magick::ImageList.new(@map_filename).first - @position_quantization_in_degrees = 0.0 - @position_visibility_threshold = 0.1 - @circle_radius = map_size[:width] / 250.0 + def initialize + @map_filename = $visualization_config.map_filename + @raw_image = Magick::ImageList.new(@map_filename).first + if $visualization_config.map_width || $visualization_config.map_height + width = $visualization_config.map_width || @raw_image.columns + height = $visualization_config.map_height || @raw_image.rows + @raw_image.resize! width, height + end + new_frame + @position_quantization_in_degrees = 10.0 + @opacity_visibility_threshold = 0.1 + @circle_radius = (map_size[:width] ** 1.25) / (map_size[:width] * $visualization_config.fill_dot_scale).to_f + @points = [] end def map_size - { :width => @image.columns, :height => @image.rows } + @map_size ||= { :width => @frame.columns, :height => @frame.rows } end def scale - { :x => 360.0 / map_size[:width], :y => 180.0 / map_size[:height] } + @scale ||= { :x => 360.0 / map_size[:width], :y => 180.0 / map_size[:height] } end def x_y_from_longitude_latitude longitude, latitude [ (180 + longitude) / scale[:x], (90 - latitude) / scale[:y] ] end def circle_parameters center_x, center_y [ center_x, center_y, center_x + circle_radius, center_y ] end def quantize_position position return position if @position_quantization_in_degrees == 0 position.collect{ |element| element - element.remainder(@position_quantization_in_degrees) } end def quantize_positions positions positions.collect{ |position| quantize_position(position) } end - def select_visible_positions positions - positions.select{ |position| position.opacity >= @position_visibility_threshold } + def select_visible_points points + points.select{ |point| point.opacity >= @opacity_visibility_threshold } end - def draw_positions actual_positions, previous_positions = [] - @draw.fill('red') - @draw.fill_opacity('50%') - - positions = actual_positions.concat(previous_positions) -# positions = select_visible_positions(positions) - positions = quantize_positions(positions) + def draw_positions positions_lon_lat + @draw.fill($visualization_config.fill_dot_color) - positions.each do |longitude, latitude| + new_points = positions_lon_lat.collect do |longitude, latitude| x, y = x_y_from_longitude_latitude(longitude, latitude) - @draw.circle(*circle_parameters(x, y)) + PointInTime.new(x, y, $visualization_config.fill_dot_opacity, $visualization_config.fill_dot_lifetime) end - @draw.draw(@image) + @points = @points.concat(new_points) + @points = select_visible_points(@points) +# positions = quantize_positions(@positions) + points = @points + + points.each do |point| + @draw.fill_opacity(point.opacity) + @draw.circle(*circle_parameters(point.x, point.y)) + point.age + end - @image + @draw.draw(@frame) + + @frame end def display - @image.display + @frame.display + end + + def new_frame + @draw = Magick::Draw.new + @frame = @raw_image.clone end end ############################################################################### # see http://en.wikipedia.org/wiki/Exponential_decay class Decay def initialize initial_value, lifetime - @initial_value = initial_value + @initial_value = initial_value.to_f @lifetime = lifetime.to_f end def value time @initial_value * Math::exp(-time / @lifetime) end end ############################################################################### class PointInTime attr_reader :x, :y def initialize x, y, initial_opacity, lifetime @x, @y = x, y @time = 0 @decay = Decay.new(initial_opacity, lifetime) end - def opacity time + def opacity_in_time time @time = time if time - @decay.value(time || @time) + @decay.value(@time) + end + + def opacity + @decay.value(@time) + end + + def age + @time += 1 end end ############################################################################### #decay = Decay.new(10, 5) -#p (0..9).collect{ |t| decay.value(t) } +#p (0..20).collect{ |t| decay.value(t) } #exit -#logfile = LogfileMock.new -#visualization = Visualization.new -#visualization.position_quantization_in_degrees = 5.0 -#visualization.draw_positions(logfile.positions) -#visualization.display +#decay = Decay.new(10, 5) +#point = PointInTime.new(0,0, 10,5) +#p (0..20).collect{ |t| point.opacity } #exit -analyzer = ApacheLogAnalyzer.new(Dir.glob(ARGV)) -analyzer.load_coordinates_from_file -details = analyzer.analyze -#grouped_details = analyzer.group_by_time(details, 3600) -grouped_details = analyzer.group_by_time(details, 86400) - -list = Magick::ImageList.new -frames_per_second = 15 - -previous_positions = [] -grouped_details.each_pair do |time, details| - visualization = Visualization.new - visualization.circle_radius = 1.0 - - visualization.position_quantization_in_degrees = 0.0 - actual_positions = details.select{ |data| data[:coordinates].any? }.collect{ |data| data[:coordinates] } -p [time, details.size, actual_positions.size] - image = visualization.draw_positions(actual_positions, previous_positions) - #previous_positions = actual_positions - previous_positions = [] - - draw = Magick::Draw.new - draw.fill('grey') - draw.fill_opacity('50%') - draw.rectangle(0.2 * visualization.map_size[:width], 0.9 * visualization.map_size[:height], 0.8 * visualization.map_size[:width], 0.9 * visualization.map_size[:height] + 30) - draw.fill('black') - draw.fill_opacity('100%') - draw.text_align(Magick::CenterAlign) - draw.pointsize(20) - draw.text(0.5 * visualization.map_size[:width], 0.9 * visualization.map_size[:height] + 20, "Time: #{time}") - draw.draw(image) - - list << image +def draw_info_background draw, size + width, height = size[:width], size[:height] + draw.fill('grey') + draw.fill_opacity('50%') + draw.rectangle(0.2 * width, 0.9 * height, 0.8 * width, 0.9 * height + 30) end -list.delay = 1000 / (frames_per_second * 10) -list.animate - -exit - - -list = Magick::ImageList.new -frames_per_second = 1 -duration = 1 -previous_positions = [] -(duration * frames_per_second).to_int.times do |i| - visualization = Visualization.new - visualization.circle_radius = 1.0 - visualization.position_quantization_in_degrees = 0.0 -# actual_positions = logfile.positions - #details = LogAnalyzer.new(Dir.glob(ARGV)).analyze - #p details - #actual_positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } - coords, ips = LogAnalyzer.new(Dir.glob(ARGV)).load_coordinates_from_file - actual_positions = coords.values.select{ |coords| coords.any? } -p actual_positions.size - image = visualization.draw_positions(actual_positions, previous_positions) - previous_positions = actual_positions - - draw = Magick::Draw.new - draw.fill('grey') - draw.fill_opacity('50%') - draw.rectangle(0.2 * visualization.map_size[:width], 0.9 * visualization.map_size[:height], 0.8 * visualization.map_size[:width], 0.9 * visualization.map_size[:height] + 30) - draw.fill('black') - draw.fill_opacity('100%') - draw.text_align(Magick::CenterAlign) - draw.pointsize(20) - draw.text(0.5 * visualization.map_size[:width], 0.9 * visualization.map_size[:height] + 20, "Frame #{i+1}") - draw.draw(image) - - list << image + +def draw_info_message draw, size, info + draw.fill('black') + draw.fill_opacity('100%') + draw.text_align(Magick::CenterAlign) + draw.pointsize(20) + draw.text(0.5 * size[:width], 0.9 * size[:height] + 20, info) +end + +def draw_info image, visualization, info + draw = Magick::Draw.new + size = { :width => visualization.map_size[:width], :height => visualization.map_size[:height] } + draw_info_background(draw, size) + draw_info_message(draw, size, info) + draw.draw(image) +end + +def detect_time_format times + some_samples = times.sort[0..99] + smallest_period = some_samples.each_cons(2).collect{ |time1, time2| (time1 - time2).abs }.min + + return '%b %d %Y %H:%M' if smallest_period < 3600 # scale: minutes + return '%b %d %Y %H:00' if smallest_period < 86400 # scale: hours + return '%b %d %Y' # scale: days +end + +def show_some_random_points + logfile = LogfileMock.new + visualization = Visualization.new + visualization.position_quantization_in_degrees = 5.0 + visualization.draw_positions(logfile.positions) + visualization.display end -list.delay = 1000 / (frames_per_second * 10) -list.animate + +def access_image + analyzer = ApacheLogAnalyzer.new(Dir.glob(ARGV)) + analyzer.load_cached_coordinates_from_file + details = analyzer.analyze + positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } + + visualization = Visualization.new + visualization.draw_positions(positions).display +end + +def access_animation + analyzer = ApacheLogAnalyzer.new(Dir.glob(ARGV)) + analyzer.load_cached_coordinates_from_file + details = analyzer.analyze + grouped_details = analyzer.group_by_time(details, $visualization_config.group_seconds) + + animation = Magick::ImageList.new + visualization = Visualization.new + time_format = $visualization_config.time_format || detect_time_format(grouped_details.keys) + + grouped_details.sort().each do |time, details| + visualization.new_frame + positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } + p [time, details.size, positions.size] + image = visualization.draw_positions(positions) + + draw_info(image, visualization, time.strftime(time_format)) + animation << image + end + + animation.delay = 1000 / ($visualization_config.frames_per_second * 10) +# animation.each_with_index{ |img, idx| p img; img.write("tng.#{'%03i' % idx}.jpg") } +# animation.write "tng.gif" + animation.animate +end + +#show_some_random_points +#access_image +access_animation
darxriggs/ip-world-map
bda17a9f08a74a5fd418a942b74c70fb35c4e532
added apache_log_analyzer to spec helper
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index bffbdca..6787f9a 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,11 +1,12 @@ begin require 'spec' rescue LoadError require 'rubygems' gem 'rspec' require 'spec' end $:.unshift(File.dirname(__FILE__) + '/../lib') +require 'apache_log_analyzer' require 'visualization'
darxriggs/ip-world-map
7ae71f0cdcbb07673883f84f637cdc2475de1a3b
added intial specs (not yet error-free)
diff --git a/spec/decay.rb b/spec/decay.rb new file mode 100644 index 0000000..7b98f74 --- /dev/null +++ b/spec/decay.rb @@ -0,0 +1,17 @@ +require File.dirname(__FILE__) + '/spec_helper.rb' + +describe PointInTime do + it 'should be initialized with either Integers and/or Floats' do + Decay.new(10, 5 ) + Decay.new(10, 5.0) + Decay.new(10.0, 5 ) + Decay.new(10.0, 5.0) + end + + it 'should return a value depending on the time' do + decay = Decay.new(10, 5) + + decay.value(0).should be 10 + decay.value(2).should be 0 # todo + end +end diff --git a/spec/point_in_time.rb b/spec/point_in_time.rb new file mode 100644 index 0000000..c436aa4 --- /dev/null +++ b/spec/point_in_time.rb @@ -0,0 +1,20 @@ +require File.dirname(__FILE__) + '/spec_helper.rb' + +describe PointInTime do + it 'should convert currencies properly' do + Currency::convert('AUD', 'USD').should > 0 + end + + it 'raise an exception on incorrect currencies' do + lambda { Currency::convert('YYY', 'XXX') }.should raise_error(Currency::RateError) + end + + it 'should process amounts properly' do + amount = 10 + result_with_amount = Currency::convert('AUD', 'USD', amount) + result_without_amount = Currency::convert('AUD', 'USD') + + result_with_amount.should == amount * result_without_amount + end +end + diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..bffbdca --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,11 @@ +begin + require 'spec' +rescue LoadError + require 'rubygems' + gem 'rspec' + require 'spec' +end + +$:.unshift(File.dirname(__FILE__) + '/../lib') + +require 'visualization'
darxriggs/ip-world-map
971d973782a187fc6b89510468827434874f40e4
added .gitignore
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..da8cb79 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*.swp +NS2_FILES +nbproject
darxriggs/ip-world-map
14f42d8d33dde5f3baabb36b68c5b98a2cf79d82
added Rakefile (only including 'test' task for the moment)
diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..42d54a0 --- /dev/null +++ b/Rakefile @@ -0,0 +1,10 @@ +require 'rubygems' +require 'spec/version' +require 'spec/rake/spectask' + +Spec::Rake::SpecTask.new('specs') do |t| + t.spec_files = FileList['spec/**/*.rb'] + t.rcov = false + t.rcov_opts = ['--exclude', 'spec'] + t.verbose = true +end
darxriggs/ip-world-map
36450d888f9df665baf033fa50778401e2c3d5ed
reorganized business logic into separate libs folder
diff --git a/apache_log_analyzer.rb b/apache_log_analyzer.rb deleted file mode 100755 index e021fe5..0000000 --- a/apache_log_analyzer.rb +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env ruby - -require 'zlib' - -#LOG_FILE = "/var/log/apache2/access.log.1" -LOG_FILE = ARGV[0] || "/var/log/apache2/access.log.2.gz" - -module FileUtils - def self.open (filename, &block) - if %w[.gz .Z].include? File.extname(filename) - Zlib::GzipReader.open(filename, &block) - else - File.open(filename, &block) - end - end -end - -module LogAnalyzer - def details_from_line line - { - :host => line.scan(/^[\w.-]+/)[0], - :date => line.scan(/\[[\w\/:+ ]+\]/)[0] - } - end - - def group_by_time access_ungrouped, window_in_seconds - access_grouped - end - - module_function :details_from_line -end - - -FileUtils.open(LOG_FILE) do |file| - lines = file.readlines[0..9] - lines.each do |line| - details = LogAnalyzer::details_from_line(line) - puts "#{details[:host]} - #{details[:date]}" - end -end diff --git a/lib/visualization.rb b/lib/visualization.rb new file mode 100755 index 0000000..d13fbf4 --- /dev/null +++ b/lib/visualization.rb @@ -0,0 +1,223 @@ +#!/usr/bin/env ruby + +require 'rubygems' +require 'RMagick' +require File.dirname(__FILE__) + "/apache_log_analyzer.rb" + +#coordinates_home = [11.6220338, 48.1276458] # Munich +#coordinates_home = [13.4114943, 52.5234802] # Berlin +#coordinates_home = [12.3387844, 45.4343363] # Venezia + +############################################################################### + +class Logfile + def initialize filename + end +end + +############################################################################### + +class LogfileMock + attr_accessor :min_random_positions, :max_random_positions + + def initialize + @min_random_positions = 5 + @max_random_positions = 50 + end + + def random_longitude_latitude + [ -10 + rand(25) + rand, 40 + rand(15) + rand ] + end + + def random_positions + amount = @min_random_positions + rand(@max_random_positions - @min_random_positions + 1) + Array.new(amount) { random_longitude_latitude } + end + alias :positions :random_positions +end + +############################################################################### + +class Visualization + attr_accessor :position_quantization_in_degrees, :circle_radius + + #def initialize filename = File.dirname(__FILE__) + "/../maps/earthmap-1920x960.tif" + def initialize filename = File.dirname(__FILE__) + "/../maps/earthmap-800x400.tif" + @map_filename = filename + @draw = Magick::Draw.new + @image = Magick::ImageList.new(@map_filename).first + @position_quantization_in_degrees = 0.0 + @position_visibility_threshold = 0.1 + @circle_radius = map_size[:width] / 250.0 + end + + def map_size + { :width => @image.columns, :height => @image.rows } + end + + def scale + { :x => 360.0 / map_size[:width], :y => 180.0 / map_size[:height] } + end + + def x_y_from_longitude_latitude longitude, latitude + [ (180 + longitude) / scale[:x], (90 - latitude) / scale[:y] ] + end + + def circle_parameters center_x, center_y + [ center_x, center_y, center_x + circle_radius, center_y ] + end + + def quantize_position position + return position if @position_quantization_in_degrees == 0 + position.collect{ |element| element - element.remainder(@position_quantization_in_degrees) } + end + + def quantize_positions positions + positions.collect{ |position| quantize_position(position) } + end + + def select_visible_positions positions + positions.select{ |position| position.opacity >= @position_visibility_threshold } + end + + def draw_positions actual_positions, previous_positions = [] + @draw.fill('red') + @draw.fill_opacity('50%') + + positions = actual_positions.concat(previous_positions) +# positions = select_visible_positions(positions) + positions = quantize_positions(positions) + + positions.each do |longitude, latitude| + x, y = x_y_from_longitude_latitude(longitude, latitude) + @draw.circle(*circle_parameters(x, y)) + end + + @draw.draw(@image) + + @image + end + + def display + @image.display + end +end + +############################################################################### + +# see http://en.wikipedia.org/wiki/Exponential_decay +class Decay + def initialize initial_value, lifetime + @initial_value = initial_value + @lifetime = lifetime.to_f + end + + def value time + @initial_value * Math::exp(-time / @lifetime) + end +end + +############################################################################### + +class PointInTime + attr_reader :x, :y + + def initialize x, y, initial_opacity, lifetime + @x, @y = x, y + @time = 0 + @decay = Decay.new(initial_opacity, lifetime) + end + + def opacity time + @time = time if time + @decay.value(time || @time) + end +end + +############################################################################### + +#decay = Decay.new(10, 5) +#p (0..9).collect{ |t| decay.value(t) } +#exit + +#logfile = LogfileMock.new +#visualization = Visualization.new +#visualization.position_quantization_in_degrees = 5.0 +#visualization.draw_positions(logfile.positions) +#visualization.display +#exit + +analyzer = ApacheLogAnalyzer.new(Dir.glob(ARGV)) +analyzer.load_coordinates_from_file +details = analyzer.analyze +#grouped_details = analyzer.group_by_time(details, 3600) +grouped_details = analyzer.group_by_time(details, 86400) + +list = Magick::ImageList.new +frames_per_second = 15 + +previous_positions = [] +grouped_details.each_pair do |time, details| + visualization = Visualization.new + visualization.circle_radius = 1.0 + + visualization.position_quantization_in_degrees = 0.0 + actual_positions = details.select{ |data| data[:coordinates].any? }.collect{ |data| data[:coordinates] } +p [time, details.size, actual_positions.size] + image = visualization.draw_positions(actual_positions, previous_positions) + #previous_positions = actual_positions + previous_positions = [] + + draw = Magick::Draw.new + draw.fill('grey') + draw.fill_opacity('50%') + draw.rectangle(0.2 * visualization.map_size[:width], 0.9 * visualization.map_size[:height], 0.8 * visualization.map_size[:width], 0.9 * visualization.map_size[:height] + 30) + draw.fill('black') + draw.fill_opacity('100%') + draw.text_align(Magick::CenterAlign) + draw.pointsize(20) + draw.text(0.5 * visualization.map_size[:width], 0.9 * visualization.map_size[:height] + 20, "Time: #{time}") + draw.draw(image) + + list << image +end +list.delay = 1000 / (frames_per_second * 10) +list.animate + +exit + + +list = Magick::ImageList.new +frames_per_second = 1 +duration = 1 +previous_positions = [] +(duration * frames_per_second).to_int.times do |i| + visualization = Visualization.new + visualization.circle_radius = 1.0 + visualization.position_quantization_in_degrees = 0.0 +# actual_positions = logfile.positions + #details = LogAnalyzer.new(Dir.glob(ARGV)).analyze + #p details + #actual_positions = details.collect{ |data| data[:coordinates] }.select{ |coords| coords.any? } + coords, ips = LogAnalyzer.new(Dir.glob(ARGV)).load_coordinates_from_file + actual_positions = coords.values.select{ |coords| coords.any? } +p actual_positions.size + image = visualization.draw_positions(actual_positions, previous_positions) + previous_positions = actual_positions + + draw = Magick::Draw.new + draw.fill('grey') + draw.fill_opacity('50%') + draw.rectangle(0.2 * visualization.map_size[:width], 0.9 * visualization.map_size[:height], 0.8 * visualization.map_size[:width], 0.9 * visualization.map_size[:height] + 30) + draw.fill('black') + draw.fill_opacity('100%') + draw.text_align(Magick::CenterAlign) + draw.pointsize(20) + draw.text(0.5 * visualization.map_size[:width], 0.9 * visualization.map_size[:height] + 20, "Frame #{i+1}") + draw.draw(image) + + list << image +end +list.delay = 1000 / (frames_per_second * 10) +list.animate + diff --git a/visualization.rb b/visualization.rb deleted file mode 100755 index fbe3686..0000000 --- a/visualization.rb +++ /dev/null @@ -1,129 +0,0 @@ -#!/usr/bin/env ruby - -require 'rubygems' -require 'RMagick' - -#coordinates_home = [11.6220338, 48.1276458] # Munich -#coordinates_home = [13.4114943, 52.5234802] # Berlin -#coordinates_home = [12.3387844, 45.4343363] # Venezia - -############################################################################### - -class Logfile - def initialize filename - end -end - -############################################################################### - -class LogfileMock - attr_accessor :min_random_positions, :max_random_positions - - def initialize - @min_random_positions = 5 - @max_random_positions = 50 - end - - def random_longitude_latitude - [ -10 + rand(25) + rand, 40 + rand(15) + rand ] - end - - def random_positions - amount = @min_random_positions + rand(@max_random_positions - @min_random_positions + 1) - Array.new(amount) { random_longitude_latitude } - end - alias :positions :random_positions -end - -############################################################################### - -class Visualization - attr_accessor :position_quantization_in_degrees, :circle_radius - - #def initialize filename = "earthmap-1600x800.tif" - def initialize filename = "earthmap-800x400.tif" - @map_filename = filename - @draw = Magick::Draw.new - @image = Magick::ImageList.new(@map_filename).first - @position_quantization_in_degrees = 0.0 - @circle_radius = map_size[:width] / 250.0 - end - - def map_size - { :width => @image.columns, :height => @image.rows } - end - - def scale - { :x => 360.0 / map_size[:width], :y => 180.0 / map_size[:height] } - end - - def x_y_from_longitude_latitude longitude, latitude - [ (180 + longitude) / scale[:x], (90 - latitude) / scale[:y] ] - end - - def circle_parameters center_x, center_y - [ center_x, center_y, center_x + circle_radius, center_y ] - end - - def quantize_position position - position.collect{ |element| element - element.remainder(@position_quantization_in_degrees) } - end - - def quantize_positions positions - positions.collect{ |position| quantize_position(position) } - end - - def draw_positions positions - @draw.fill('red') - @draw.fill_opacity('50%') - - positions = quantize_positions(positions) - - positions.each do |longitude, latitude| - x, y = x_y_from_longitude_latitude(longitude, latitude) - @draw.circle(*circle_parameters(x, y)) - end - - @draw.draw(@image) - - @image - end - - def display - @image.display - end -end - -############################################################################### - -logfile = LogfileMock.new -#visualization = Visualization.new -#visualization.position_quantization_in_degrees = 5.0 -#visualization.draw_positions(logfile.positions) -#visualization.display -#exit - -list = Magick::ImageList.new -frames_per_second = 15 -duration = 2 -(duration * frames_per_second).to_int.times do |i| - visualization = Visualization.new - visualization.position_quantization_in_degrees = 1.0 - image = visualization.draw_positions(logfile.positions) - - draw = Magick::Draw.new - draw.fill('grey') - draw.fill_opacity('50%') - draw.rectangle(0.2 * visualization.map_size[:width], 0.9 * visualization.map_size[:height], 0.8 * visualization.map_size[:width], 0.9 * visualization.map_size[:height] + 30) - draw.fill('black') - draw.fill_opacity('100%') - draw.text_align(Magick::CenterAlign) - draw.pointsize(20) - draw.text(0.5 * visualization.map_size[:width], 0.9 * visualization.map_size[:height] + 20, "Frame #{i+1}") - draw.draw(image) - - list << image -end -list.delay = 1000 / (frames_per_second * 10) -list.animate -
darxriggs/ip-world-map
cb35c545c5f518232bde5b65a83950ec261f400f
reorganized maps into separate folder
diff --git a/access_map.README b/access_map.README deleted file mode 100644 index 041bd1e..0000000 --- a/access_map.README +++ /dev/null @@ -1,4 +0,0 @@ -User story: -As a website host -I want to show a video with the access locations printed on a world map -To get an overview where my customers are based. diff --git a/maps/earthmap-10800x5400.jpg b/maps/earthmap-10800x5400.jpg new file mode 100644 index 0000000..812458c Binary files /dev/null and b/maps/earthmap-10800x5400.jpg differ diff --git a/earthmap-1600x800.tif b/maps/earthmap-1600x800.tif similarity index 100% rename from earthmap-1600x800.tif rename to maps/earthmap-1600x800.tif diff --git a/maps/earthmap-1920x960.tif b/maps/earthmap-1920x960.tif new file mode 100644 index 0000000..30ca2bc Binary files /dev/null and b/maps/earthmap-1920x960.tif differ diff --git a/earthmap-800x400.tif b/maps/earthmap-800x400.tif similarity index 100% rename from earthmap-800x400.tif rename to maps/earthmap-800x400.tif diff --git a/maps/earthmap-8192x4096.tif b/maps/earthmap-8192x4096.tif new file mode 100644 index 0000000..79c4e3c Binary files /dev/null and b/maps/earthmap-8192x4096.tif differ diff --git a/maps/earthmap.readme b/maps/earthmap.readme new file mode 100644 index 0000000..fd95d38 --- /dev/null +++ b/maps/earthmap.readme @@ -0,0 +1,5 @@ +This file is in the public domain because it was created by NASA. +NASA copyright policy states that "NASA material is not protected by copyright unless noted". + +http://commons.wikimedia.org/wiki/File:Whole_world_-_land_and_oceans_12000.jpg +http://visibleearth.nasa.gov/view_rec.php?vev1id=11656
darxriggs/ip-world-map
e44a15fc42aefeca0f4dc9316365494034550a72
added support for log file analysis - generic class for log files - subclass for Apache format
diff --git a/lib/apache_log_analyzer.rb b/lib/apache_log_analyzer.rb new file mode 100755 index 0000000..3d6c424 --- /dev/null +++ b/lib/apache_log_analyzer.rb @@ -0,0 +1,159 @@ +#!/usr/bin/env ruby + +require 'zlib' +require 'time' +require 'date' +require 'net/http' +require 'yaml' + +module FileUtils + def self.zipped? filename + %w[.gz .Z].include? File.extname(filename) + end + + def self.open (filename, &block) + if zipped? filename + Zlib::GzipReader.open(filename, &block) + else + File.open(filename, &block) + end + end +end + + +class LogAnalyzer + attr_accessor :host_coordinates + + def initialize *filenames + @filenames = filenames.flatten.sort.uniq + @host_coordinates = {} + @host_ips = {} + end + + def ip_for_host host + is_ip?(host) ? host : Socket.getaddrinfo(host, nil)[0][3] rescue nil + end + + def is_ip? string + /^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$/.match(string) != nil + end + + def coordinates_for_host host + unless @host_coordinates[host] + @host_ips[host] ||= ip_for_host(host) + + response = Net::HTTP.get('api.hostip.info', "/get_html.php?position=true&ip=#{@host_ips[host]}").split(/\n/) + latitude = response[2].match(/Latitude: (-?[0-9.]+)/)[1].to_f rescue nil + longitude = response[3].match(/Longitude: (-?[0-9.]+)/)[1].to_f rescue nil + @host_coordinates[host] = [longitude, latitude] + end + + @host_coordinates[host] + end + + def details_from_line line + host = extract_host_from_line(line) + time = extract_time_from_line(line) + coordinates = coordinates_for_host(host) + + { :time => time, :host => host, :coordinates => coordinates } + end + + def analyze + details = [] + + @filenames.each do |filename| + puts filename + FileUtils.open(filename) do |file| + lines = file.readlines + lines.each do |line| + details << details_from_line(line) + end + end + end + + details + end + + def save_coordinates_to_file filename = 'coordinates.yml' + File.open(filename, 'w'){ |f| f.write @host_coordinates.to_yaml } + end + + def load_coordinates_from_file filename = 'coordinates.yml' + @host_coordinates = YAML.load_file(filename) + end + + def stats + unknown_coordinates, known_coordinates = @host_coordinates.partition{ |ip, coords| coords.include? nil } + + { :unknown_coordinates => unknown_coordinates.size, :known_coordinates => known_coordinates.size } + end + + def group_by_time details, slot_in_seconds + latest_time = details.min{ |a,b| a[:time] <=> b[:time] }[:time] + slot_time = slot_start_time(latest_time, slot_in_seconds) + details_per_slot = {} + + # quite slow algorithm +# while details.count > 0 do +# slot_cap_time = slot_time + slot_in_seconds +# details_in_slot, details = details.partition{ |data| data[:time] < slot_cap_time } +# details_per_slot[slot_time] = details_in_slot +# slot_time = slot_cap_time +# end + + # TODO: maybe assign empty arrays to missing slots where no traffic was detected + details.each do |data| + time = slot_start_time(data[:time], slot_in_seconds) + details_per_slot[time] = [] unless details_per_slot[time] + details_per_slot[time] << data + end + + details_per_slot + end + + def slot_start_time time, slot_in_seconds + Time.at(time.tv_sec - (time.tv_sec % slot_in_seconds)) + end +end + + +class ApacheLogAnalyzer < LogAnalyzer + def initialize *filenames + super + @@host_regex = /^([\w.-]+)/ + @@time_regex = /\[(\d{2})\/([a-zA-Z]{3})\/(\d{4}):(\d{2}):(\d{2}):(\d{2}) [+-](\d{2})(\d{2})\]/ + end + + def extract_host_from_line line + # IP: "123.1.2.3" or HOSTNAME: "hostname.domain" + host = $1 if line =~ @@host_regex + end + + def extract_time_from_line line + # CLF format: "[dd/MMM/yyyy:hh:mm:ss +-hhmm]" => parsable format: "dd/MMM/yyyy hh:mm:ss +-hhmm" + + # 1. quite slow + # time_string = line.scan(/\[[\w\/:+ ]+\]/).first[1...-1].sub(':', ' ') + # Time.parse(time_string) + + # 2. TODO: add timezone information + #dd, mmm, yyyy, hh, mm, ss, tz_hh, tz_mm = $1, $2, $3, $4, $5, $6, $7, $8 if line =~ @@time_regex + #Time.utc(yyyy, mmm, dd, hh.to_i - tz_hh.to_i, mm, ss) + dd, mmm, yyyy, hh, mm, ss = $1, $2, $3, $4, $5, $6 if line =~ @@time_regex + Time.utc(yyyy, mmm, dd, hh, mm, ss) + end +end + + +if $0 == __FILE__ + analyzer = ApacheLogAnalyzer.new(Dir.glob(ARGV)) + analyzer.load_coordinates_from_file + + details = analyzer.analyze + details_per_slot = analyzer.group_by_time(details, 24 * 60 * 60) + + p analyzer.stats + details_per_slot.sort().each{ |slot, values| p "#{slot}: #{values.size}" } + p details_per_slot.size +end
darxriggs/ip-world-map
f9282b88399437b82357cdca3fdf8789598f7c00
started visualization
diff --git a/visualization.rb b/visualization.rb new file mode 100755 index 0000000..fbe3686 --- /dev/null +++ b/visualization.rb @@ -0,0 +1,129 @@ +#!/usr/bin/env ruby + +require 'rubygems' +require 'RMagick' + +#coordinates_home = [11.6220338, 48.1276458] # Munich +#coordinates_home = [13.4114943, 52.5234802] # Berlin +#coordinates_home = [12.3387844, 45.4343363] # Venezia + +############################################################################### + +class Logfile + def initialize filename + end +end + +############################################################################### + +class LogfileMock + attr_accessor :min_random_positions, :max_random_positions + + def initialize + @min_random_positions = 5 + @max_random_positions = 50 + end + + def random_longitude_latitude + [ -10 + rand(25) + rand, 40 + rand(15) + rand ] + end + + def random_positions + amount = @min_random_positions + rand(@max_random_positions - @min_random_positions + 1) + Array.new(amount) { random_longitude_latitude } + end + alias :positions :random_positions +end + +############################################################################### + +class Visualization + attr_accessor :position_quantization_in_degrees, :circle_radius + + #def initialize filename = "earthmap-1600x800.tif" + def initialize filename = "earthmap-800x400.tif" + @map_filename = filename + @draw = Magick::Draw.new + @image = Magick::ImageList.new(@map_filename).first + @position_quantization_in_degrees = 0.0 + @circle_radius = map_size[:width] / 250.0 + end + + def map_size + { :width => @image.columns, :height => @image.rows } + end + + def scale + { :x => 360.0 / map_size[:width], :y => 180.0 / map_size[:height] } + end + + def x_y_from_longitude_latitude longitude, latitude + [ (180 + longitude) / scale[:x], (90 - latitude) / scale[:y] ] + end + + def circle_parameters center_x, center_y + [ center_x, center_y, center_x + circle_radius, center_y ] + end + + def quantize_position position + position.collect{ |element| element - element.remainder(@position_quantization_in_degrees) } + end + + def quantize_positions positions + positions.collect{ |position| quantize_position(position) } + end + + def draw_positions positions + @draw.fill('red') + @draw.fill_opacity('50%') + + positions = quantize_positions(positions) + + positions.each do |longitude, latitude| + x, y = x_y_from_longitude_latitude(longitude, latitude) + @draw.circle(*circle_parameters(x, y)) + end + + @draw.draw(@image) + + @image + end + + def display + @image.display + end +end + +############################################################################### + +logfile = LogfileMock.new +#visualization = Visualization.new +#visualization.position_quantization_in_degrees = 5.0 +#visualization.draw_positions(logfile.positions) +#visualization.display +#exit + +list = Magick::ImageList.new +frames_per_second = 15 +duration = 2 +(duration * frames_per_second).to_int.times do |i| + visualization = Visualization.new + visualization.position_quantization_in_degrees = 1.0 + image = visualization.draw_positions(logfile.positions) + + draw = Magick::Draw.new + draw.fill('grey') + draw.fill_opacity('50%') + draw.rectangle(0.2 * visualization.map_size[:width], 0.9 * visualization.map_size[:height], 0.8 * visualization.map_size[:width], 0.9 * visualization.map_size[:height] + 30) + draw.fill('black') + draw.fill_opacity('100%') + draw.text_align(Magick::CenterAlign) + draw.pointsize(20) + draw.text(0.5 * visualization.map_size[:width], 0.9 * visualization.map_size[:height] + 20, "Frame #{i+1}") + draw.draw(image) + + list << image +end +list.delay = 1000 / (frames_per_second * 10) +list.animate +
darxriggs/ip-world-map
340f2ca339a674b0069e34b871d8b0c2e4abf8bd
added 2 earth maps of size 800x400 and 1600x800
diff --git a/earthmap-1600x800.tif b/earthmap-1600x800.tif new file mode 100644 index 0000000..ad5dd6c Binary files /dev/null and b/earthmap-1600x800.tif differ diff --git a/earthmap-800x400.tif b/earthmap-800x400.tif new file mode 100644 index 0000000..947a7d0 Binary files /dev/null and b/earthmap-800x400.tif differ
darxriggs/ip-world-map
5c003e47514bf15a0b679ad404d9e5772c0c5cde
initial load
diff --git a/access_map.README b/access_map.README new file mode 100644 index 0000000..041bd1e --- /dev/null +++ b/access_map.README @@ -0,0 +1,4 @@ +User story: +As a website host +I want to show a video with the access locations printed on a world map +To get an overview where my customers are based. diff --git a/animation.gif b/animation.gif new file mode 100644 index 0000000..0faf6d7 Binary files /dev/null and b/animation.gif differ diff --git a/apache_log_analyzer.rb b/apache_log_analyzer.rb new file mode 100755 index 0000000..e021fe5 --- /dev/null +++ b/apache_log_analyzer.rb @@ -0,0 +1,40 @@ +#!/usr/bin/env ruby + +require 'zlib' + +#LOG_FILE = "/var/log/apache2/access.log.1" +LOG_FILE = ARGV[0] || "/var/log/apache2/access.log.2.gz" + +module FileUtils + def self.open (filename, &block) + if %w[.gz .Z].include? File.extname(filename) + Zlib::GzipReader.open(filename, &block) + else + File.open(filename, &block) + end + end +end + +module LogAnalyzer + def details_from_line line + { + :host => line.scan(/^[\w.-]+/)[0], + :date => line.scan(/\[[\w\/:+ ]+\]/)[0] + } + end + + def group_by_time access_ungrouped, window_in_seconds + access_grouped + end + + module_function :details_from_line +end + + +FileUtils.open(LOG_FILE) do |file| + lines = file.readlines[0..9] + lines.each do |line| + details = LogAnalyzer::details_from_line(line) + puts "#{details[:host]} - #{details[:date]}" + end +end diff --git a/htc.jpg b/htc.jpg new file mode 100644 index 0000000..32cbea8 Binary files /dev/null and b/htc.jpg differ diff --git a/htc2.jpg b/htc2.jpg new file mode 100644 index 0000000..75793f1 Binary files /dev/null and b/htc2.jpg differ diff --git a/images.rb b/images.rb new file mode 100755 index 0000000..3afcec3 --- /dev/null +++ b/images.rb @@ -0,0 +1,22 @@ +#!/usr/bin/env ruby + +require 'rubygems' +require 'RMagick' + +# show an image +#im = Magick::ImageList.new("htc.jpg") +#im.display + +# draw a half-transparent red circle +im = Magick::ImageList.new("htc.jpg") +draw = Magick::Draw.new +draw.fill('red') +draw.fill_opacity('50%') +draw.circle(200, 200, 50, 200) +draw.draw(im) +im.display + +# generate an animated image out of 2 images +#im = Magick::ImageList.new("htc.jpg", "htc2.jpg") +#im.write("animation.gif") +
kineticsocial/rabbitmq_snmp_plugin
79326c792e0ea73788c16ae9c7b73a91af1f3d5c
try/catch around the trace so if we happend to send an invalid pid we will not crash
diff --git a/src/rabbit_snmp_tracer.erl b/src/rabbit_snmp_tracer.erl index 1030e57..1c6067d 100644 --- a/src/rabbit_snmp_tracer.erl +++ b/src/rabbit_snmp_tracer.erl @@ -1,76 +1,84 @@ -module(rabbit_snmp_tracer). -behaviour(gen_server). -export([start/0, start/2, stop/0, stop/1, start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([start_trace/1, stop_trace/1]). -record(state, {table}). start() -> start_link(), ok. start(normal, []) -> start_link(). stop() -> ok. stop(_State) -> stop(). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). init([]) -> Table = ets:new(queue_throughput_stats, []), {ok, #state{table = Table}}. handle_call({start_trace, Pid}, _From, State) -> ets:insert(State#state.table, {Pid, 0}), - erlang:trace(Pid, true, [{tracer, self()}, 'receive']), + try erlang:trace(Pid, true, [{tracer, self()}, 'receive']) + catch + error:badarg -> error_logger:warning_msg("Unable to enable trace of pid: ~p~n", [Pid]), ok; + _:_ -> ok + end, {reply, ok, State}; handle_call({stop_trace, Pid}, _From, State) -> ets:delete(State#state.table, Pid), - erlang:trace(Pid, false, [{tracer, self()}, 'receive']), + try erlang:trace(Pid, false, [{tracer, self()}, 'receive']) + catch + error:badarg -> error_logger:warning_msg("Unable to disable trace of pid: ~p~n", [Pid]), ok; + _:_ -> ok + end, {reply, ok, State}; handle_call({get_count, Pid}, _From, State) -> Result = case ets:lookup(State#state.table, Pid) of [] -> no_stats; [{Pid, Count}] -> Count end, {reply, Result, State}; handle_call(_Msg,_From,State) -> %io:format("Call: ~p~nState: ~p~n", [Msg, State]), {reply, unknown_command, State}. handle_cast(_Msg,State) -> %io:format("Cast: ~p~nState: ~p~n", [Msg, State]), {noreply, State}. handle_info({trace, Pid, 'receive', {'$gen_cast', {deliver,_,_,_}}}, State) -> ets:update_counter(State#state.table, Pid, 1), {noreply, State}; handle_info(_Info, State) -> {noreply, State}. start_trace(Pid) -> io:format("Starting Trace of: ~p~n", [Pid]), gen_server:call(?MODULE, {start_trace, Pid}). stop_trace(Pid) -> io:format("Stopping Trace of: ~p~n", [Pid]), gen_server:call(?MODULE, {stop_trace, Pid}). terminate(_,_State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}.
kineticsocial/rabbitmq_snmp_plugin
8a41beccdf3538cda509c437c1e39cc82ed71cf5
properly handle return from environment
diff --git a/src/rabbit_snmp_worker.erl b/src/rabbit_snmp_worker.erl index 01c7402..0c77841 100644 --- a/src/rabbit_snmp_worker.erl +++ b/src/rabbit_snmp_worker.erl @@ -1,128 +1,128 @@ -module(rabbit_snmp_worker). -behaviour(gen_server). -export([start/0, start/2, stop/0, stop/1, start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {update_interval}). start() -> start_link(), ok. start(normal, []) -> start_link(). stop() -> ok. stop(_State) -> stop(). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). init([]) -> application:start(snmp), UpdateInterval = case application:get_env(rabbit_snmp, update_interval) of undefined -> 10000; - Value -> Value + {ok, Value} -> Value end, io:format("Started snmp state poller w/~pms interval~n", [UpdateInterval]), erlang:send_after(1, self(), update_stats), {ok, #state{update_interval = UpdateInterval}}. create_exchange_row([]) -> ok; create_exchange_row([Row|Rest]) -> {exchange, {resource, Vhost, exchange, ExchangeName}, ExchangeType, ExchangeDurability, ExchangeAutoDelete, _Args} = Row, ListVhost = binary_to_list(Vhost), ListExchange = binary_to_list(ExchangeName), SnmpRow = {ListVhost, ListExchange, atom_to_list(ExchangeType), ExchangeDurability, ExchangeAutoDelete }, snmpa_local_db:table_create_row(exchangeTable, ListVhost ++ ListExchange, SnmpRow), create_exchange_row(Rest). create_vhost_row([]) -> ok; create_vhost_row([Row|Rest]) -> {Vhost, QueueCount, ExchangeCount, MessageCount} = Row, ListVhost = binary_to_list(Vhost), SnmpRow = {ListVhost, QueueCount, ExchangeCount, MessageCount}, snmpa_local_db:table_create_row(vhostTable, ListVhost, SnmpRow), create_vhost_row(Rest). create_queue_row([]) -> ok; create_queue_row([Row|Rest]) -> {resource, Vhost, queue, QueueName} = proplists:get_value(name, Row), ListVhost = binary_to_list(Vhost), ListQueue = binary_to_list(QueueName), QueuePid = proplists:get_value(pid, Row), MessagesSent = case gen_server:call(rabbit_snmp_tracer, {get_count, QueuePid}) of no_stats -> gen_server:call(rabbit_snmp_tracer, {start_trace, QueuePid}), 0; Count -> Count end, SnmpRow = {ListVhost, ListQueue, proplists:get_value(durable, Row), proplists:get_value(auto_delete, Row), proplists:get_value(messages, Row), proplists:get_value(messages_unacknowledged, Row), proplists:get_value(messages_uncommitted, Row), proplists:get_value(messages_ready, Row), proplists:get_value(acks_uncommitted, Row), proplists:get_value(consumers, Row), proplists:get_value(transactions, Row), proplists:get_value(memory, Row), MessagesSent }, snmpa_local_db:table_create_row(queueTable, ListVhost ++ ListQueue, SnmpRow), create_queue_row(Rest). sum_queue_info(InfoAll, Name) -> lists:foldl(fun(Props, Acc) -> Acc + proplists:get_value(Name, Props) end, 0, InfoAll). update_stats() -> Vhosts = rabbit_access_control:list_vhosts(), VhostsQueuesAndExchanges = [{X, rabbit_amqqueue:info_all(X), rabbit_exchange:list(X)} || X <- Vhosts], VhostRows = [{X, length(Q), length(E), sum_queue_info(Q, messages)} || {X,Q,E} <- VhostsQueuesAndExchanges], create_vhost_row(VhostRows), QueueRows = lists:append([Q || {_,Q,_} <- VhostsQueuesAndExchanges]), create_queue_row(QueueRows), ExchangeRows = lists:append([E || {_,_,E} <- VhostsQueuesAndExchanges]), create_exchange_row(ExchangeRows), ok. handle_call(_Msg,_From,State) -> {reply, unknown_command, State}. handle_cast(_,State) -> {noreply, State}. handle_info(update_stats, State) -> update_stats(), erlang:send_after(State#state.update_interval, self(), update_stats), {noreply, State}; handle_info(Info, State) -> io:format("Info: ~p~nState: ~p~n", [Info, State]), {noreply, State}. terminate(_,_State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}.
kineticsocial/rabbitmq_snmp_plugin
b85c128236cf15a9b20dcace95bc655b77eb4da4
10 second update interval by default
diff --git a/src/rabbit_snmp_worker.erl b/src/rabbit_snmp_worker.erl index c827fa1..01c7402 100644 --- a/src/rabbit_snmp_worker.erl +++ b/src/rabbit_snmp_worker.erl @@ -1,128 +1,128 @@ -module(rabbit_snmp_worker). -behaviour(gen_server). -export([start/0, start/2, stop/0, stop/1, start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {update_interval}). start() -> start_link(), ok. start(normal, []) -> start_link(). stop() -> ok. stop(_State) -> stop(). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). init([]) -> application:start(snmp), UpdateInterval = case application:get_env(rabbit_snmp, update_interval) of - undefined -> 1000; + undefined -> 10000; Value -> Value end, io:format("Started snmp state poller w/~pms interval~n", [UpdateInterval]), erlang:send_after(1, self(), update_stats), {ok, #state{update_interval = UpdateInterval}}. create_exchange_row([]) -> ok; create_exchange_row([Row|Rest]) -> {exchange, {resource, Vhost, exchange, ExchangeName}, ExchangeType, ExchangeDurability, ExchangeAutoDelete, _Args} = Row, ListVhost = binary_to_list(Vhost), ListExchange = binary_to_list(ExchangeName), SnmpRow = {ListVhost, ListExchange, atom_to_list(ExchangeType), ExchangeDurability, ExchangeAutoDelete }, snmpa_local_db:table_create_row(exchangeTable, ListVhost ++ ListExchange, SnmpRow), create_exchange_row(Rest). create_vhost_row([]) -> ok; create_vhost_row([Row|Rest]) -> {Vhost, QueueCount, ExchangeCount, MessageCount} = Row, ListVhost = binary_to_list(Vhost), SnmpRow = {ListVhost, QueueCount, ExchangeCount, MessageCount}, snmpa_local_db:table_create_row(vhostTable, ListVhost, SnmpRow), create_vhost_row(Rest). create_queue_row([]) -> ok; create_queue_row([Row|Rest]) -> {resource, Vhost, queue, QueueName} = proplists:get_value(name, Row), ListVhost = binary_to_list(Vhost), ListQueue = binary_to_list(QueueName), QueuePid = proplists:get_value(pid, Row), MessagesSent = case gen_server:call(rabbit_snmp_tracer, {get_count, QueuePid}) of no_stats -> gen_server:call(rabbit_snmp_tracer, {start_trace, QueuePid}), 0; Count -> Count end, SnmpRow = {ListVhost, ListQueue, proplists:get_value(durable, Row), proplists:get_value(auto_delete, Row), proplists:get_value(messages, Row), proplists:get_value(messages_unacknowledged, Row), proplists:get_value(messages_uncommitted, Row), proplists:get_value(messages_ready, Row), proplists:get_value(acks_uncommitted, Row), proplists:get_value(consumers, Row), proplists:get_value(transactions, Row), proplists:get_value(memory, Row), MessagesSent }, snmpa_local_db:table_create_row(queueTable, ListVhost ++ ListQueue, SnmpRow), create_queue_row(Rest). sum_queue_info(InfoAll, Name) -> lists:foldl(fun(Props, Acc) -> Acc + proplists:get_value(Name, Props) end, 0, InfoAll). update_stats() -> Vhosts = rabbit_access_control:list_vhosts(), VhostsQueuesAndExchanges = [{X, rabbit_amqqueue:info_all(X), rabbit_exchange:list(X)} || X <- Vhosts], VhostRows = [{X, length(Q), length(E), sum_queue_info(Q, messages)} || {X,Q,E} <- VhostsQueuesAndExchanges], create_vhost_row(VhostRows), QueueRows = lists:append([Q || {_,Q,_} <- VhostsQueuesAndExchanges]), create_queue_row(QueueRows), ExchangeRows = lists:append([E || {_,_,E} <- VhostsQueuesAndExchanges]), create_exchange_row(ExchangeRows), ok. handle_call(_Msg,_From,State) -> {reply, unknown_command, State}. handle_cast(_,State) -> {noreply, State}. handle_info(update_stats, State) -> update_stats(), erlang:send_after(State#state.update_interval, self(), update_stats), {noreply, State}; handle_info(Info, State) -> io:format("Info: ~p~nState: ~p~n", [Info, State]), {noreply, State}. terminate(_,_State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}.
kineticsocial/rabbitmq_snmp_plugin
a0fd1cef7062f67c56274b33e13e0afd61425bc6
Trace messages going to the queues so we can get the number of messages delivered
diff --git a/snmp/RABBITMQ-MIB.mib b/snmp/RABBITMQ-MIB.mib index 9fce880..e384396 100644 --- a/snmp/RABBITMQ-MIB.mib +++ b/snmp/RABBITMQ-MIB.mib @@ -1,262 +1,270 @@ RABBITMQ-MIB DEFINITIONS ::= BEGIN -- -- Top-level infrastructure of the Epic Ads enterprise MIB tree -- IMPORTS MODULE-IDENTITY, OBJECT-TYPE, Gauge32, Counter64, enterprises FROM SNMPv2-SMI OBJECT-GROUP FROM SNMPv2-CONF DisplayString, TruthValue FROM SNMPv2-TC; rabbitMQ MODULE-IDENTITY LAST-UPDATED "200911040000Z" ORGANIZATION "www.epicadvertising.com" CONTACT-INFO "e-mail: scott.brooks@epicadvertising.com" DESCRIPTION "RabbitMQ snmp mib" REVISION "200911040000Z" DESCRIPTION "First draft" ::= { enterprises 12346} rabbitGroups OBJECT IDENTIFIER ::= { rabbitMQ 1 } vhosts OBJECT IDENTIFIER ::= { rabbitMQ 2 } queues OBJECT IDENTIFIER ::= { rabbitMQ 3 } exchanges OBJECT IDENTIFIER ::= { rabbitMQ 4 } vhostTable OBJECT-TYPE SYNTAX SEQUENCE OF VhostEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "list of vhosts" ::= { vhosts 1 } vhostTableEntry OBJECT-TYPE SYNTAX VhostEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "vhost entry" INDEX { vhostName } ::= { vhostTable 1 } VhostEntry ::= SEQUENCE { vhostName DisplayString, vhostQueueCount Gauge32, vhostExchangeCount Gauge32, vhostMessageCount Gauge32 } vhostName OBJECT-TYPE SYNTAX DisplayString MAX-ACCESS read-only STATUS current DESCRIPTION "Vhost name" ::= { vhostTableEntry 1 } vhostQueueCount OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Count of queues for a specific vhost" ::= { vhostTableEntry 2 } vhostExchangeCount OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Count of exchanges for a specific vhost" ::= { vhostTableEntry 3 } vhostMessageCount OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Count of messages for a specific vhost" ::= { vhostTableEntry 4 } queueTable OBJECT-TYPE SYNTAX SEQUENCE OF QueueStatisticsEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "A list of all the queues for a specific vhost" ::= { queues 1 } queueTableEntry OBJECT-TYPE SYNTAX QueueStatisticsEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "A queue" INDEX { queueVhost, queueName } ::= { queueTable 1 } QueueStatisticsEntry ::= SEQUENCE { queueVhost DisplayString, queueName DisplayString, queueDurable TruthValue, queueAutoDelete TruthValue, queueMessages Gauge32, queueUnAcknowledged Gauge32, queueUnCommitted Gauge32, queueReady Gauge32, queueAcksUncommitted Gauge32, queueConsumers Gauge32, queueTransactions Gauge32, - queueMemory Counter64 + queueMemory Counter64, + queueMessagesDelivered Counter64 } queueVhost OBJECT-TYPE SYNTAX DisplayString MAX-ACCESS read-only STATUS current DESCRIPTION "Queue Vhost" ::= { queueTableEntry 1 } queueName OBJECT-TYPE SYNTAX DisplayString MAX-ACCESS read-only STATUS current DESCRIPTION "Queue name" ::= { queueTableEntry 2 } queueDurable OBJECT-TYPE SYNTAX TruthValue MAX-ACCESS read-only STATUS current DESCRIPTION "True if the queue is durable" ::= { queueTableEntry 3 } queueAutoDelete OBJECT-TYPE SYNTAX TruthValue MAX-ACCESS read-only STATUS current DESCRIPTION "True if the queue is set to auto_delete" ::= { queueTableEntry 4 } queueMessages OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Number of messages" ::= { queueTableEntry 5 } queueUnAcknowledged OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Number of unacknowledged messages" ::= { queueTableEntry 6 } queueUnCommitted OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Number of uncommitted messages" ::= { queueTableEntry 7 } queueReady OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Number of ready messages" ::= { queueTableEntry 8 } queueAcksUncommitted OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Number of uncommitted acks" ::= { queueTableEntry 9 } queueConsumers OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Number of consumers" ::= { queueTableEntry 10 } queueTransactions OBJECT-TYPE SYNTAX Gauge32 MAX-ACCESS read-only STATUS current DESCRIPTION "Number of transactions" ::= { queueTableEntry 11 } queueMemory OBJECT-TYPE SYNTAX Counter64 MAX-ACCESS read-only STATUS current DESCRIPTION "Amount of memory used" ::= { queueTableEntry 12 } +queueMessagesDelivered OBJECT-TYPE + SYNTAX Counter64 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Number of messages delivered to this queue" + ::= { queueTableEntry 13 } + exchangeTable OBJECT-TYPE SYNTAX SEQUENCE OF ExchangeEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "list of exchanges" ::= { exchanges 1 } exchangeTableEntry OBJECT-TYPE SYNTAX ExchangeEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "exchange entry" INDEX { exchangeVhost, exchangeName } ::= { exchangeTable 1 } ExchangeEntry ::= SEQUENCE { exchangeVhost DisplayString, exchangeName DisplayString, exchangeType DisplayString, exchangeDurable TruthValue, exchangeAutoDelete TruthValue } exchangeVhost OBJECT-TYPE SYNTAX DisplayString MAX-ACCESS read-only STATUS current DESCRIPTION "Exchange Vhost" ::= { exchangeTableEntry 1 } exchangeName OBJECT-TYPE SYNTAX DisplayString MAX-ACCESS read-only STATUS current DESCRIPTION "Exchange name" ::= { exchangeTableEntry 2 } exchangeType OBJECT-TYPE SYNTAX DisplayString MAX-ACCESS read-only STATUS current DESCRIPTION "Exchange Type" ::= { exchangeTableEntry 3 } exchangeDurable OBJECT-TYPE SYNTAX TruthValue MAX-ACCESS read-only STATUS current DESCRIPTION "True if the queue is set to durable" ::= { exchangeTableEntry 4 } exchangeAutoDelete OBJECT-TYPE SYNTAX TruthValue MAX-ACCESS read-only STATUS current DESCRIPTION "True if the queue is set to auto_delete" ::= { exchangeTableEntry 5 } rabbitGroup OBJECT-GROUP OBJECTS { - vhostQueueCount, vhostExchangeCount, vhostMessageCount, queueVhost, queueName, queueDurable, queueAutoDelete, queueMessages, queueUnAcknowledged, queueUnCommitted, queueReady, queueAcksUncommitted, queueConsumers, queueTransactions, queueMemory, vhostName, exchangeVhost, exchangeType, exchangeName, exchangeDurable, exchangeAutoDelete + vhostQueueCount, vhostExchangeCount, vhostMessageCount, queueVhost, queueName, queueDurable, queueAutoDelete, queueMessages, queueUnAcknowledged, queueUnCommitted, queueReady, queueAcksUncommitted, queueConsumers, queueTransactions, queueMemory, queueMessagesDelivered, vhostName, exchangeVhost, exchangeType, exchangeName, exchangeDurable, exchangeAutoDelete } STATUS current DESCRIPTION "Groups" ::= { rabbitGroups 1 } END diff --git a/src/rabbit_snmp_sup.erl b/src/rabbit_snmp_sup.erl index 1617c9b..f0d3fe5 100644 --- a/src/rabbit_snmp_sup.erl +++ b/src/rabbit_snmp_sup.erl @@ -1,17 +1,23 @@ -module(rabbit_snmp_sup). -behaviour(supervisor). -export([start_link/0, init/1]). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, _Arg = []). init([]) -> {ok, {{one_for_one, 3, 10}, - [{rabbit_snmp_worker, + [{rabbit_snmp_tracer, + {rabbit_snmp_tracer, start_link, []}, + permanent, + 10000, + worker, + [rabbit_snmp_tracer]}, + {rabbit_snmp_worker, {rabbit_snmp_worker, start_link, []}, permanent, 10000, worker, [rabbit_snmp_worker]} - ]}}. + ]}}. diff --git a/src/rabbit_snmp_tracer.erl b/src/rabbit_snmp_tracer.erl new file mode 100644 index 0000000..1030e57 --- /dev/null +++ b/src/rabbit_snmp_tracer.erl @@ -0,0 +1,76 @@ +-module(rabbit_snmp_tracer). +-behaviour(gen_server). + +-export([start/0, start/2, stop/0, stop/1, start_link/0]). +-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). + +-export([start_trace/1, stop_trace/1]). + +-record(state, {table}). + +start() -> + start_link(), + ok. + +start(normal, []) -> + start_link(). + +stop() -> + ok. + +stop(_State) -> + stop(). + +start_link() -> + gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). + +init([]) -> + Table = ets:new(queue_throughput_stats, []), + {ok, #state{table = Table}}. + +handle_call({start_trace, Pid}, _From, State) -> + ets:insert(State#state.table, {Pid, 0}), + erlang:trace(Pid, true, [{tracer, self()}, 'receive']), + {reply, ok, State}; + +handle_call({stop_trace, Pid}, _From, State) -> + ets:delete(State#state.table, Pid), + erlang:trace(Pid, false, [{tracer, self()}, 'receive']), + {reply, ok, State}; + +handle_call({get_count, Pid}, _From, State) -> + Result = case ets:lookup(State#state.table, Pid) of + [] -> no_stats; + [{Pid, Count}] -> Count + end, + {reply, Result, State}; + +handle_call(_Msg,_From,State) -> + %io:format("Call: ~p~nState: ~p~n", [Msg, State]), + {reply, unknown_command, State}. + +handle_cast(_Msg,State) -> + %io:format("Cast: ~p~nState: ~p~n", [Msg, State]), + {noreply, State}. + +handle_info({trace, Pid, 'receive', {'$gen_cast', {deliver,_,_,_}}}, State) -> + ets:update_counter(State#state.table, Pid, 1), + {noreply, State}; + +handle_info(_Info, State) -> + {noreply, State}. + +start_trace(Pid) -> + io:format("Starting Trace of: ~p~n", [Pid]), + gen_server:call(?MODULE, {start_trace, Pid}). + +stop_trace(Pid) -> + io:format("Stopping Trace of: ~p~n", [Pid]), + gen_server:call(?MODULE, {stop_trace, Pid}). + +terminate(_,_State) -> + ok. + +code_change(_OldVsn, State, _Extra) -> + {ok, State}. + diff --git a/src/rabbit_snmp_worker.erl b/src/rabbit_snmp_worker.erl index a4201fb..c827fa1 100644 --- a/src/rabbit_snmp_worker.erl +++ b/src/rabbit_snmp_worker.erl @@ -1,119 +1,128 @@ -module(rabbit_snmp_worker). -behaviour(gen_server). -export([start/0, start/2, stop/0, stop/1, start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {update_interval}). start() -> start_link(), ok. start(normal, []) -> start_link(). stop() -> ok. stop(_State) -> stop(). start_link() -> - gen_server:start_link({global, ?MODULE}, ?MODULE, [], []). + gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). init([]) -> application:start(snmp), - {ok, UpdateInterval} = application:get_env(rabbit_snmp, update_interval), + UpdateInterval = case application:get_env(rabbit_snmp, update_interval) of + undefined -> 1000; + Value -> Value + end, io:format("Started snmp state poller w/~pms interval~n", [UpdateInterval]), erlang:send_after(1, self(), update_stats), {ok, #state{update_interval = UpdateInterval}}. create_exchange_row([]) -> ok; create_exchange_row([Row|Rest]) -> {exchange, {resource, Vhost, exchange, ExchangeName}, ExchangeType, ExchangeDurability, ExchangeAutoDelete, _Args} = Row, ListVhost = binary_to_list(Vhost), ListExchange = binary_to_list(ExchangeName), SnmpRow = {ListVhost, ListExchange, atom_to_list(ExchangeType), ExchangeDurability, ExchangeAutoDelete }, snmpa_local_db:table_create_row(exchangeTable, ListVhost ++ ListExchange, SnmpRow), create_exchange_row(Rest). create_vhost_row([]) -> ok; create_vhost_row([Row|Rest]) -> {Vhost, QueueCount, ExchangeCount, MessageCount} = Row, ListVhost = binary_to_list(Vhost), SnmpRow = {ListVhost, QueueCount, ExchangeCount, MessageCount}, snmpa_local_db:table_create_row(vhostTable, ListVhost, SnmpRow), create_vhost_row(Rest). create_queue_row([]) -> ok; create_queue_row([Row|Rest]) -> {resource, Vhost, queue, QueueName} = proplists:get_value(name, Row), ListVhost = binary_to_list(Vhost), ListQueue = binary_to_list(QueueName), + QueuePid = proplists:get_value(pid, Row), + MessagesSent = case gen_server:call(rabbit_snmp_tracer, {get_count, QueuePid}) of + no_stats -> gen_server:call(rabbit_snmp_tracer, {start_trace, QueuePid}), 0; + Count -> Count + end, SnmpRow = {ListVhost, ListQueue, proplists:get_value(durable, Row), proplists:get_value(auto_delete, Row), proplists:get_value(messages, Row), proplists:get_value(messages_unacknowledged, Row), proplists:get_value(messages_uncommitted, Row), proplists:get_value(messages_ready, Row), proplists:get_value(acks_uncommitted, Row), proplists:get_value(consumers, Row), proplists:get_value(transactions, Row), - proplists:get_value(memory, Row) + proplists:get_value(memory, Row), + MessagesSent }, snmpa_local_db:table_create_row(queueTable, ListVhost ++ ListQueue, SnmpRow), create_queue_row(Rest). sum_queue_info(InfoAll, Name) -> lists:foldl(fun(Props, Acc) -> Acc + proplists:get_value(Name, Props) end, 0, InfoAll). update_stats() -> Vhosts = rabbit_access_control:list_vhosts(), VhostsQueuesAndExchanges = [{X, rabbit_amqqueue:info_all(X), rabbit_exchange:list(X)} || X <- Vhosts], VhostRows = [{X, length(Q), length(E), sum_queue_info(Q, messages)} || {X,Q,E} <- VhostsQueuesAndExchanges], create_vhost_row(VhostRows), QueueRows = lists:append([Q || {_,Q,_} <- VhostsQueuesAndExchanges]), create_queue_row(QueueRows), ExchangeRows = lists:append([E || {_,_,E} <- VhostsQueuesAndExchanges]), create_exchange_row(ExchangeRows), ok. handle_call(_Msg,_From,State) -> {reply, unknown_command, State}. handle_cast(_,State) -> {noreply, State}. handle_info(update_stats, State) -> update_stats(), erlang:send_after(State#state.update_interval, self(), update_stats), {noreply, State}; handle_info(Info, State) -> io:format("Info: ~p~nState: ~p~n", [Info, State]), {noreply, State}. terminate(_,_State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}.
kineticsocial/rabbitmq_snmp_plugin
48511b3754fc3cfc489955ce5ed5607743ef10da
4 spaces rather then tabs
diff --git a/src/rabbit_snmp.erl b/src/rabbit_snmp.erl index 948632c..e1459a3 100644 --- a/src/rabbit_snmp.erl +++ b/src/rabbit_snmp.erl @@ -1,34 +1,34 @@ -module(rabbit_snmp). -export([start/0, stop/0, start/2, stop/1]). -include("RABBITMQ-MIB.hrl"). load_snmp_environment() -> - Path = code:lib_dir(rabbitmq,snmp), + Path = code:lib_dir(rabbitmq,snmp), - ok = application:load(snmp), - {ok, Agent} = application:get_env(snmp, agent), - Config = proplists:get_value(config, Agent), - NewConfig = lists:keystore(dir, 1, Config, {dir, Path ++ "/agent/conf"}), - NewAgent = lists:keystore(db_dir, 1, (lists:keystore(config, 1, Agent, {config, NewConfig})), {db_dir, Path ++ "/agent/db"}), - application:set_env(snmp, agent, NewAgent), + ok = application:load(snmp), + {ok, Agent} = application:get_env(snmp, agent), + Config = proplists:get_value(config, Agent), + NewConfig = lists:keystore(dir, 1, Config, {dir, Path ++ "/agent/conf"}), + NewAgent = lists:keystore(db_dir, 1, (lists:keystore(config, 1, Agent, {config, NewConfig})), {db_dir, Path ++ "/agent/db"}), + application:set_env(snmp, agent, NewAgent), - ok = application:start(snmp), - ok = snmpa:load_mibs(snmp_master_agent, [Path ++ "/RABBITMQ-MIB"]), - ok. + ok = application:start(snmp), + ok = snmpa:load_mibs(snmp_master_agent, [Path ++ "/RABBITMQ-MIB"]), + ok. start() -> - load_snmp_environment(), - rabbit_snmp_sup:start_link(), - ok. + load_snmp_environment(), + rabbit_snmp_sup:start_link(), + ok. stop() -> - ok. + ok. start(normal, []) -> - load_snmp_environment(), - rabbit_snmp_sup:start_link(). + load_snmp_environment(), + rabbit_snmp_sup:start_link(). stop(_State) -> - ok. + ok. diff --git a/src/rabbit_snmp_sup.erl b/src/rabbit_snmp_sup.erl index 232a561..1617c9b 100644 --- a/src/rabbit_snmp_sup.erl +++ b/src/rabbit_snmp_sup.erl @@ -1,17 +1,17 @@ -module(rabbit_snmp_sup). -behaviour(supervisor). -export([start_link/0, init/1]). start_link() -> - supervisor:start_link({local, ?MODULE}, ?MODULE, _Arg = []). + supervisor:start_link({local, ?MODULE}, ?MODULE, _Arg = []). init([]) -> - {ok, {{one_for_one, 3, 10}, - [{rabbit_snmp_worker, - {rabbit_snmp_worker, start_link, []}, - permanent, - 10000, - worker, - [rabbit_snmp_worker]} - ]}}. + {ok, {{one_for_one, 3, 10}, + [{rabbit_snmp_worker, + {rabbit_snmp_worker, start_link, []}, + permanent, + 10000, + worker, + [rabbit_snmp_worker]} + ]}}.
kineticsocial/rabbitmq_snmp_plugin
d1410e9b7156caa20825a4b7f5232bedeefd05c4
added aggregated vhost data points (queues, exchanges, messages)
diff --git a/snmp/RABBITMQ-MIB.mib b/snmp/RABBITMQ-MIB.mib index 7e0f6aa..9fce880 100644 --- a/snmp/RABBITMQ-MIB.mib +++ b/snmp/RABBITMQ-MIB.mib @@ -1,238 +1,262 @@ RABBITMQ-MIB DEFINITIONS ::= BEGIN -- -- Top-level infrastructure of the Epic Ads enterprise MIB tree -- IMPORTS - MODULE-IDENTITY, OBJECT-TYPE, Gauge32, Counter64, enterprises FROM SNMPv2-SMI + MODULE-IDENTITY, OBJECT-TYPE, Gauge32, Counter64, enterprises FROM SNMPv2-SMI - OBJECT-GROUP FROM SNMPv2-CONF + OBJECT-GROUP FROM SNMPv2-CONF - DisplayString, TruthValue FROM SNMPv2-TC; + DisplayString, TruthValue FROM SNMPv2-TC; - rabbitMQ MODULE-IDENTITY - LAST-UPDATED "200911040000Z" - ORGANIZATION "www.epicadvertising.com" - CONTACT-INFO - "e-mail: scott.brooks@epicadvertising.com" - DESCRIPTION - "RabbitMQ snmp mib" - REVISION "200911040000Z" - DESCRIPTION - "First draft" - ::= { enterprises 12346} + rabbitMQ MODULE-IDENTITY + LAST-UPDATED "200911040000Z" + ORGANIZATION "www.epicadvertising.com" + CONTACT-INFO + "e-mail: scott.brooks@epicadvertising.com" + DESCRIPTION + "RabbitMQ snmp mib" + REVISION "200911040000Z" + DESCRIPTION + "First draft" + ::= { enterprises 12346} rabbitGroups OBJECT IDENTIFIER ::= { rabbitMQ 1 } vhosts OBJECT IDENTIFIER ::= { rabbitMQ 2 } queues OBJECT IDENTIFIER ::= { rabbitMQ 3 } exchanges OBJECT IDENTIFIER ::= { rabbitMQ 4 } vhostTable OBJECT-TYPE - SYNTAX SEQUENCE OF VhostEntry - MAX-ACCESS not-accessible - STATUS current - DESCRIPTION "list of vhosts" - ::= { vhosts 1 } + SYNTAX SEQUENCE OF VhostEntry + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION "list of vhosts" + ::= { vhosts 1 } vhostTableEntry OBJECT-TYPE - SYNTAX VhostEntry - MAX-ACCESS not-accessible - STATUS current - DESCRIPTION "vhost entry" - INDEX { vhostName } - ::= { vhostTable 1 } + SYNTAX VhostEntry + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION "vhost entry" + INDEX { vhostName } + ::= { vhostTable 1 } VhostEntry ::= SEQUENCE { - vhostName DisplayString + vhostName DisplayString, + vhostQueueCount Gauge32, + vhostExchangeCount Gauge32, + vhostMessageCount Gauge32 } vhostName OBJECT-TYPE - SYNTAX DisplayString - MAX-ACCESS read-only - STATUS current - DESCRIPTION "Vhost name" - ::= { vhostTableEntry 1 } + SYNTAX DisplayString + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Vhost name" + ::= { vhostTableEntry 1 } + +vhostQueueCount OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Count of queues for a specific vhost" + ::= { vhostTableEntry 2 } + +vhostExchangeCount OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Count of exchanges for a specific vhost" + ::= { vhostTableEntry 3 } + +vhostMessageCount OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Count of messages for a specific vhost" + ::= { vhostTableEntry 4 } queueTable OBJECT-TYPE - SYNTAX SEQUENCE OF QueueStatisticsEntry - MAX-ACCESS not-accessible - STATUS current - DESCRIPTION "A list of all the queues for a specific vhost" - ::= { queues 1 } + SYNTAX SEQUENCE OF QueueStatisticsEntry + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION "A list of all the queues for a specific vhost" + ::= { queues 1 } queueTableEntry OBJECT-TYPE - SYNTAX QueueStatisticsEntry - MAX-ACCESS not-accessible - STATUS current - DESCRIPTION "A queue" - INDEX { queueVhost, queueName } - ::= { queueTable 1 } + SYNTAX QueueStatisticsEntry + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION "A queue" + INDEX { queueVhost, queueName } + ::= { queueTable 1 } QueueStatisticsEntry ::= SEQUENCE { - queueVhost DisplayString, - queueName DisplayString, - queueDurable TruthValue, - queueAutoDelete TruthValue, - queueMessages Gauge32, - queueUnAcknowledged Gauge32, - queueUnCommitted Gauge32, - queueReady Gauge32, - queueAcksUncommitted Gauge32, - queueConsumers Gauge32, - queueTransactions Gauge32, - queueMemory Counter64 + queueVhost DisplayString, + queueName DisplayString, + queueDurable TruthValue, + queueAutoDelete TruthValue, + queueMessages Gauge32, + queueUnAcknowledged Gauge32, + queueUnCommitted Gauge32, + queueReady Gauge32, + queueAcksUncommitted Gauge32, + queueConsumers Gauge32, + queueTransactions Gauge32, + queueMemory Counter64 } queueVhost OBJECT-TYPE - SYNTAX DisplayString - MAX-ACCESS read-only - STATUS current - DESCRIPTION "Queue Vhost" - ::= { queueTableEntry 1 } + SYNTAX DisplayString + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Queue Vhost" + ::= { queueTableEntry 1 } queueName OBJECT-TYPE - SYNTAX DisplayString - MAX-ACCESS read-only - STATUS current - DESCRIPTION "Queue name" - ::= { queueTableEntry 2 } + SYNTAX DisplayString + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Queue name" + ::= { queueTableEntry 2 } queueDurable OBJECT-TYPE - SYNTAX TruthValue - MAX-ACCESS read-only - STATUS current - DESCRIPTION "True if the queue is durable" - ::= { queueTableEntry 3 } + SYNTAX TruthValue + MAX-ACCESS read-only + STATUS current + DESCRIPTION "True if the queue is durable" + ::= { queueTableEntry 3 } queueAutoDelete OBJECT-TYPE - SYNTAX TruthValue - MAX-ACCESS read-only - STATUS current - DESCRIPTION "True if the queue is set to auto_delete" - ::= { queueTableEntry 4 } + SYNTAX TruthValue + MAX-ACCESS read-only + STATUS current + DESCRIPTION "True if the queue is set to auto_delete" + ::= { queueTableEntry 4 } queueMessages OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION "Number of messages" - ::= { queueTableEntry 5 } + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Number of messages" + ::= { queueTableEntry 5 } queueUnAcknowledged OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION "Number of unacknowledged messages" - ::= { queueTableEntry 6 } + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Number of unacknowledged messages" + ::= { queueTableEntry 6 } queueUnCommitted OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION "Number of uncommitted messages" - ::= { queueTableEntry 7 } + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Number of uncommitted messages" + ::= { queueTableEntry 7 } queueReady OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION "Number of ready messages" - ::= { queueTableEntry 8 } + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Number of ready messages" + ::= { queueTableEntry 8 } queueAcksUncommitted OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION "Number of uncommitted acks" - ::= { queueTableEntry 9 } + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Number of uncommitted acks" + ::= { queueTableEntry 9 } queueConsumers OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION "Number of consumers" - ::= { queueTableEntry 10 } + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Number of consumers" + ::= { queueTableEntry 10 } queueTransactions OBJECT-TYPE - SYNTAX Gauge32 - MAX-ACCESS read-only - STATUS current - DESCRIPTION "Number of transactions" - ::= { queueTableEntry 11 } + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Number of transactions" + ::= { queueTableEntry 11 } queueMemory OBJECT-TYPE - SYNTAX Counter64 - MAX-ACCESS read-only - STATUS current - DESCRIPTION "Amount of memory used" - ::= { queueTableEntry 12 } + SYNTAX Counter64 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Amount of memory used" + ::= { queueTableEntry 12 } exchangeTable OBJECT-TYPE - SYNTAX SEQUENCE OF ExchangeEntry - MAX-ACCESS not-accessible - STATUS current - DESCRIPTION "list of exchanges" - ::= { exchanges 1 } + SYNTAX SEQUENCE OF ExchangeEntry + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION "list of exchanges" + ::= { exchanges 1 } exchangeTableEntry OBJECT-TYPE - SYNTAX ExchangeEntry - MAX-ACCESS not-accessible - STATUS current - DESCRIPTION "exchange entry" - INDEX { exchangeVhost, exchangeName } - ::= { exchangeTable 1 } + SYNTAX ExchangeEntry + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION "exchange entry" + INDEX { exchangeVhost, exchangeName } + ::= { exchangeTable 1 } ExchangeEntry ::= SEQUENCE { - exchangeVhost DisplayString, - exchangeName DisplayString, - exchangeType DisplayString, - exchangeDurable TruthValue, - exchangeAutoDelete TruthValue + exchangeVhost DisplayString, + exchangeName DisplayString, + exchangeType DisplayString, + exchangeDurable TruthValue, + exchangeAutoDelete TruthValue } exchangeVhost OBJECT-TYPE - SYNTAX DisplayString - MAX-ACCESS read-only - STATUS current - DESCRIPTION "Exchange Vhost" - ::= { exchangeTableEntry 1 } + SYNTAX DisplayString + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Exchange Vhost" + ::= { exchangeTableEntry 1 } exchangeName OBJECT-TYPE - SYNTAX DisplayString - MAX-ACCESS read-only - STATUS current - DESCRIPTION "Exchange name" - ::= { exchangeTableEntry 2 } + SYNTAX DisplayString + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Exchange name" + ::= { exchangeTableEntry 2 } exchangeType OBJECT-TYPE - SYNTAX DisplayString - MAX-ACCESS read-only - STATUS current - DESCRIPTION "Exchange Type" - ::= { exchangeTableEntry 3 } + SYNTAX DisplayString + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Exchange Type" + ::= { exchangeTableEntry 3 } exchangeDurable OBJECT-TYPE - SYNTAX TruthValue - MAX-ACCESS read-only - STATUS current - DESCRIPTION "True if the queue is set to durable" - ::= { exchangeTableEntry 4 } + SYNTAX TruthValue + MAX-ACCESS read-only + STATUS current + DESCRIPTION "True if the queue is set to durable" + ::= { exchangeTableEntry 4 } exchangeAutoDelete OBJECT-TYPE - SYNTAX TruthValue - MAX-ACCESS read-only - STATUS current - DESCRIPTION "True if the queue is set to auto_delete" - ::= { exchangeTableEntry 5 } + SYNTAX TruthValue + MAX-ACCESS read-only + STATUS current + DESCRIPTION "True if the queue is set to auto_delete" + ::= { exchangeTableEntry 5 } rabbitGroup OBJECT-GROUP - OBJECTS { - queueVhost, queueName, queueDurable, queueAutoDelete, queueMessages, queueUnAcknowledged, queueUnCommitted, queueReady, queueAcksUncommitted, queueConsumers, queueTransactions, queueMemory, vhostName, exchangeVhost, exchangeType, exchangeName, exchangeDurable, exchangeAutoDelete - } - STATUS current - DESCRIPTION "Groups" - ::= { rabbitGroups 1 } + OBJECTS { + vhostQueueCount, vhostExchangeCount, vhostMessageCount, queueVhost, queueName, queueDurable, queueAutoDelete, queueMessages, queueUnAcknowledged, queueUnCommitted, queueReady, queueAcksUncommitted, queueConsumers, queueTransactions, queueMemory, vhostName, exchangeVhost, exchangeType, exchangeName, exchangeDurable, exchangeAutoDelete + } + STATUS current + DESCRIPTION "Groups" + ::= { rabbitGroups 1 } END diff --git a/src/rabbit_snmp_worker.erl b/src/rabbit_snmp_worker.erl index d565faf..a4201fb 100644 --- a/src/rabbit_snmp_worker.erl +++ b/src/rabbit_snmp_worker.erl @@ -1,108 +1,119 @@ -module(rabbit_snmp_worker). -behaviour(gen_server). -export([start/0, start/2, stop/0, stop/1, start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {update_interval}). start() -> start_link(), ok. start(normal, []) -> start_link(). stop() -> ok. stop(_State) -> stop(). start_link() -> gen_server:start_link({global, ?MODULE}, ?MODULE, [], []). init([]) -> application:start(snmp), {ok, UpdateInterval} = application:get_env(rabbit_snmp, update_interval), io:format("Started snmp state poller w/~pms interval~n", [UpdateInterval]), erlang:send_after(1, self(), update_stats), {ok, #state{update_interval = UpdateInterval}}. create_exchange_row([]) -> ok; create_exchange_row([Row|Rest]) -> {exchange, {resource, Vhost, exchange, ExchangeName}, ExchangeType, ExchangeDurability, ExchangeAutoDelete, _Args} = Row, ListVhost = binary_to_list(Vhost), ListExchange = binary_to_list(ExchangeName), SnmpRow = {ListVhost, ListExchange, atom_to_list(ExchangeType), ExchangeDurability, ExchangeAutoDelete }, snmpa_local_db:table_create_row(exchangeTable, ListVhost ++ ListExchange, SnmpRow), create_exchange_row(Rest). create_vhost_row([]) -> ok; create_vhost_row([Row|Rest]) -> - SnmpRow = {binary_to_list(Row)}, - snmpa_local_db:table_create_row(vhostTable, binary_to_list(Row), SnmpRow), + {Vhost, QueueCount, ExchangeCount, MessageCount} = Row, + ListVhost = binary_to_list(Vhost), + SnmpRow = {ListVhost, QueueCount, ExchangeCount, MessageCount}, + snmpa_local_db:table_create_row(vhostTable, ListVhost, SnmpRow), create_vhost_row(Rest). create_queue_row([]) -> ok; create_queue_row([Row|Rest]) -> {resource, Vhost, queue, QueueName} = proplists:get_value(name, Row), ListVhost = binary_to_list(Vhost), ListQueue = binary_to_list(QueueName), SnmpRow = {ListVhost, ListQueue, proplists:get_value(durable, Row), proplists:get_value(auto_delete, Row), proplists:get_value(messages, Row), proplists:get_value(messages_unacknowledged, Row), proplists:get_value(messages_uncommitted, Row), proplists:get_value(messages_ready, Row), proplists:get_value(acks_uncommitted, Row), proplists:get_value(consumers, Row), proplists:get_value(transactions, Row), proplists:get_value(memory, Row) }, snmpa_local_db:table_create_row(queueTable, ListVhost ++ ListQueue, SnmpRow), create_queue_row(Rest). +sum_queue_info(InfoAll, Name) -> + lists:foldl(fun(Props, Acc) -> Acc + proplists:get_value(Name, Props) end, + 0, + InfoAll). update_stats() -> Vhosts = rabbit_access_control:list_vhosts(), - create_vhost_row(Vhosts), - Queues = lists:append([rabbit_amqqueue:info_all(X) || X <- Vhosts]), - create_queue_row(Queues), - Exchanges = lists:append([rabbit_exchange:list(X) || X <- Vhosts]), - create_exchange_row(Exchanges), + VhostsQueuesAndExchanges = [{X, rabbit_amqqueue:info_all(X), rabbit_exchange:list(X)} || X <- Vhosts], + + VhostRows = [{X, length(Q), length(E), sum_queue_info(Q, messages)} || {X,Q,E} <- VhostsQueuesAndExchanges], + create_vhost_row(VhostRows), + + QueueRows = lists:append([Q || {_,Q,_} <- VhostsQueuesAndExchanges]), + create_queue_row(QueueRows), + + ExchangeRows = lists:append([E || {_,_,E} <- VhostsQueuesAndExchanges]), + create_exchange_row(ExchangeRows), ok. handle_call(_Msg,_From,State) -> {reply, unknown_command, State}. handle_cast(_,State) -> {noreply, State}. handle_info(update_stats, State) -> update_stats(), erlang:send_after(State#state.update_interval, self(), update_stats), {noreply, State}; handle_info(Info, State) -> io:format("Info: ~p~nState: ~p~n", [Info, State]), {noreply, State}. terminate(_,_State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}.
kineticsocial/rabbitmq_snmp_plugin
d9a8ee25f2ac7a5cd30c88c829c4371b02695caf
made update interval configurable. added gitignore
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8a28226 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +ebin +dist +include/RABBITMQ-MIB.hrl +snmp/RABBITMQ-MIB.bin diff --git a/README b/README index e5088c4..11600be 100644 --- a/README +++ b/README @@ -1,48 +1,56 @@ This is an experimental RabbitMQ plugin to provide SNMP statistics. It has yet to see production use. BUILD INSTRUCTIONS: based off of: http://www.rabbitmq.com/plugin-development.html 1: Setup your rabbitmq build environment $ hg clone http://hg.rabbitmq.com/rabbitmq-public-umbrella $ make co 2: Switch to the rabbitmq_v1_7_0 tag for rabbitmq-server(a dependency for rabbit_snmp) $ cd rabbitmq-server $ hg checkout -r rabbitmq_v1_7_0 3: Make the server $ make 4: Build the rabbitmq_snmp_plugin $ cd ../rabbitmq-snmp-plugin $ make 5: Install the dist/rabbitmq-snmp.ez plugin into your server. +6: Add the following to you RabbitMQ configuration (usually /etc/rabbitmq/rabbitmq.config): + + {rabbit_snmp, + [ + % set the desired data update interval in milliseconds + {update_interval, 10000} + ] + }, {snmp, [ {agent, [ % db_dir will be set by the snmp plugin before it starts snmp so leave this commented out %{db_dir, ""}, {versions, [v1, v2]}, % dir will be added by the snmp plugin before it starts snmp, so dont add it to the config block below {config, [{verbosity, silence}]}, {net_if, [{verbosity, silence}]} ]}, {verbosity, silence} ]} Test instructions. 1: snmp walk $ snmpwalk -v 1 -c public 127.0.0.1:4001 1.3.6.1.4 Notes: The oids are named off the vhost/name combo so you can add/remove them without worrying about changing their indexes. Contact: Scott Brooks <scott.brooks@epicadvertising.com> diff --git a/src/rabbit_snmp_worker.erl b/src/rabbit_snmp_worker.erl index bf40a43..d565faf 100644 --- a/src/rabbit_snmp_worker.erl +++ b/src/rabbit_snmp_worker.erl @@ -1,108 +1,108 @@ -module(rabbit_snmp_worker). -behaviour(gen_server). -export([start/0, start/2, stop/0, stop/1, start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {update_interval}). start() -> - start_link(), - ok. + start_link(), + ok. start(normal, []) -> - start_link(). + start_link(). stop() -> - ok. + ok. stop(_State) -> - stop(). + stop(). start_link() -> - gen_server:start_link({global, ?MODULE}, ?MODULE, [], []). + gen_server:start_link({global, ?MODULE}, ?MODULE, [], []). init([]) -> - application:start(snmp), - io:format("Started snmp state poller~n", []), - UpdateInterval = 10000, - erlang:send_after(1, self(), update_stats), - {ok, #state{update_interval = UpdateInterval}}. + application:start(snmp), + {ok, UpdateInterval} = application:get_env(rabbit_snmp, update_interval), + io:format("Started snmp state poller w/~pms interval~n", [UpdateInterval]), + erlang:send_after(1, self(), update_stats), + {ok, #state{update_interval = UpdateInterval}}. create_exchange_row([]) -> - ok; + ok; create_exchange_row([Row|Rest]) -> - {exchange, {resource, Vhost, exchange, ExchangeName}, ExchangeType, ExchangeDurability, ExchangeAutoDelete, _Args} = Row, - ListVhost = binary_to_list(Vhost), - ListExchange = binary_to_list(ExchangeName), - - SnmpRow = {ListVhost, ListExchange, - atom_to_list(ExchangeType), - ExchangeDurability, - ExchangeAutoDelete - }, - snmpa_local_db:table_create_row(exchangeTable, ListVhost ++ ListExchange, SnmpRow), - create_exchange_row(Rest). + {exchange, {resource, Vhost, exchange, ExchangeName}, ExchangeType, ExchangeDurability, ExchangeAutoDelete, _Args} = Row, + ListVhost = binary_to_list(Vhost), + ListExchange = binary_to_list(ExchangeName), + + SnmpRow = {ListVhost, ListExchange, + atom_to_list(ExchangeType), + ExchangeDurability, + ExchangeAutoDelete + }, + snmpa_local_db:table_create_row(exchangeTable, ListVhost ++ ListExchange, SnmpRow), + create_exchange_row(Rest). create_vhost_row([]) -> - ok; + ok; create_vhost_row([Row|Rest]) -> - SnmpRow = {binary_to_list(Row)}, - snmpa_local_db:table_create_row(vhostTable, binary_to_list(Row), SnmpRow), - create_vhost_row(Rest). + SnmpRow = {binary_to_list(Row)}, + snmpa_local_db:table_create_row(vhostTable, binary_to_list(Row), SnmpRow), + create_vhost_row(Rest). create_queue_row([]) -> - ok; + ok; create_queue_row([Row|Rest]) -> - {resource, Vhost, queue, QueueName} = proplists:get_value(name, Row), - ListVhost = binary_to_list(Vhost), - ListQueue = binary_to_list(QueueName), - - SnmpRow = {ListVhost, ListQueue, - proplists:get_value(durable, Row), - proplists:get_value(auto_delete, Row), - proplists:get_value(messages, Row), - proplists:get_value(messages_unacknowledged, Row), - proplists:get_value(messages_uncommitted, Row), - proplists:get_value(messages_ready, Row), - proplists:get_value(acks_uncommitted, Row), - proplists:get_value(consumers, Row), - proplists:get_value(transactions, Row), - proplists:get_value(memory, Row) - }, - - snmpa_local_db:table_create_row(queueTable, ListVhost ++ ListQueue, SnmpRow), - create_queue_row(Rest). + {resource, Vhost, queue, QueueName} = proplists:get_value(name, Row), + ListVhost = binary_to_list(Vhost), + ListQueue = binary_to_list(QueueName), + + SnmpRow = {ListVhost, ListQueue, + proplists:get_value(durable, Row), + proplists:get_value(auto_delete, Row), + proplists:get_value(messages, Row), + proplists:get_value(messages_unacknowledged, Row), + proplists:get_value(messages_uncommitted, Row), + proplists:get_value(messages_ready, Row), + proplists:get_value(acks_uncommitted, Row), + proplists:get_value(consumers, Row), + proplists:get_value(transactions, Row), + proplists:get_value(memory, Row) + }, + + snmpa_local_db:table_create_row(queueTable, ListVhost ++ ListQueue, SnmpRow), + create_queue_row(Rest). update_stats() -> - Vhosts = rabbit_access_control:list_vhosts(), - create_vhost_row(Vhosts), - Queues = lists:append([rabbit_amqqueue:info_all(X) || X <- Vhosts]), - create_queue_row(Queues), - Exchanges = lists:append([rabbit_exchange:list(X) || X <- Vhosts]), - create_exchange_row(Exchanges), - ok. + Vhosts = rabbit_access_control:list_vhosts(), + create_vhost_row(Vhosts), + Queues = lists:append([rabbit_amqqueue:info_all(X) || X <- Vhosts]), + create_queue_row(Queues), + Exchanges = lists:append([rabbit_exchange:list(X) || X <- Vhosts]), + create_exchange_row(Exchanges), + ok. handle_call(_Msg,_From,State) -> - {reply, unknown_command, State}. + {reply, unknown_command, State}. handle_cast(_,State) -> - {noreply, State}. + {noreply, State}. handle_info(update_stats, State) -> - update_stats(), - erlang:send_after(State#state.update_interval, self(), update_stats), - {noreply, State}; + update_stats(), + erlang:send_after(State#state.update_interval, self(), update_stats), + {noreply, State}; handle_info(Info, State) -> - io:format("Info: ~p~nState: ~p~n", [Info, State]), - {noreply, State}. + io:format("Info: ~p~nState: ~p~n", [Info, State]), + {noreply, State}. terminate(_,_State) -> - ok. + ok. code_change(_OldVsn, State, _Extra) -> - {ok, State}. + {ok, State}.
kineticsocial/rabbitmq_snmp_plugin
2ea6567056f04b2b26022aa0811aa6db8c47583d
place holder file so the db directory gets created
diff --git a/snmp/agent/db/README b/snmp/agent/db/README new file mode 100644 index 0000000..fcfd99f --- /dev/null +++ b/snmp/agent/db/README @@ -0,0 +1 @@ +Nothing to see here, just this file to make git create the snmp/agent/db directory for us since it doesn't store empty directories
kineticsocial/rabbitmq_snmp_plugin
8268af20f516aea5367a9714bdd9acd7dd6cd9c3
fix contact e-mail address
diff --git a/README b/README index 04b0d10..e5088c4 100644 --- a/README +++ b/README @@ -1,48 +1,48 @@ This is an experimental RabbitMQ plugin to provide SNMP statistics. It has yet to see production use. BUILD INSTRUCTIONS: based off of: http://www.rabbitmq.com/plugin-development.html 1: Setup your rabbitmq build environment $ hg clone http://hg.rabbitmq.com/rabbitmq-public-umbrella $ make co 2: Switch to the rabbitmq_v1_7_0 tag for rabbitmq-server(a dependency for rabbit_snmp) $ cd rabbitmq-server $ hg checkout -r rabbitmq_v1_7_0 3: Make the server $ make 4: Build the rabbitmq_snmp_plugin $ cd ../rabbitmq-snmp-plugin $ make 5: Install the dist/rabbitmq-snmp.ez plugin into your server. {snmp, [ {agent, [ % db_dir will be set by the snmp plugin before it starts snmp so leave this commented out %{db_dir, ""}, {versions, [v1, v2]}, % dir will be added by the snmp plugin before it starts snmp, so dont add it to the config block below {config, [{verbosity, silence}]}, {net_if, [{verbosity, silence}]} ]}, {verbosity, silence} ]} Test instructions. 1: snmp walk $ snmpwalk -v 1 -c public 127.0.0.1:4001 1.3.6.1.4 Notes: The oids are named off the vhost/name combo so you can add/remove them without worrying about changing their indexes. Contact: -Scott Brooks <scott.brooks@epic-advertising.com> +Scott Brooks <scott.brooks@epicadvertising.com>
kineticsocial/rabbitmq_snmp_plugin
b8b8d2b2bad931a2a626df1af9961ba0209295c9
initial source drop
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e90c7ae --- /dev/null +++ b/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010 Epic Advertising + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..325a114 --- /dev/null +++ b/Makefile @@ -0,0 +1,13 @@ +PACKAGE=rabbitmq-snmp +DEPS= +EXTRA_PACKAGE_DIRS=snmp + +include ../include.mk + + +ebin/rabbit_snmp.beam: include/RABBITMQ-MIB.hrl snmp/RABBITMQ-MIB.bin + +snmp/RABBITMQ-MIB.bin: snmp/RABBITMQ-MIB.mib + erlc -o snmp/ $< +include/RABBITMQ-MIB.hrl: snmp/RABBITMQ-MIB.bin + erlc -o include/ $< diff --git a/README b/README index 10108ea..04b0d10 100644 --- a/README +++ b/README @@ -1 +1,48 @@ -This is an experimental RabbitMQ plugin to provide SNMP statistics. +This is an experimental RabbitMQ plugin to provide SNMP statistics. It has yet to see production use. + + +BUILD INSTRUCTIONS: + +based off of: http://www.rabbitmq.com/plugin-development.html + +1: Setup your rabbitmq build environment + $ hg clone http://hg.rabbitmq.com/rabbitmq-public-umbrella + $ make co + +2: Switch to the rabbitmq_v1_7_0 tag for rabbitmq-server(a dependency for rabbit_snmp) + $ cd rabbitmq-server + $ hg checkout -r rabbitmq_v1_7_0 + +3: Make the server + $ make + +4: Build the rabbitmq_snmp_plugin + $ cd ../rabbitmq-snmp-plugin + $ make + +5: Install the dist/rabbitmq-snmp.ez plugin into your server. + + {snmp, [ + {agent, [ + % db_dir will be set by the snmp plugin before it starts snmp so leave this commented out + %{db_dir, ""}, + {versions, [v1, v2]}, + % dir will be added by the snmp plugin before it starts snmp, so dont add it to the config block below + {config, [{verbosity, silence}]}, + {net_if, [{verbosity, silence}]} + ]}, + {verbosity, silence} + ]} + +Test instructions. + +1: snmp walk + $ snmpwalk -v 1 -c public 127.0.0.1:4001 1.3.6.1.4 + +Notes: + The oids are named off the vhost/name combo so you can add/remove them without worrying about changing their indexes. + + +Contact: +Scott Brooks <scott.brooks@epic-advertising.com> + diff --git a/ebin/rabbit_snmp.app b/ebin/rabbit_snmp.app new file mode 100644 index 0000000..f77a688 --- /dev/null +++ b/ebin/rabbit_snmp.app @@ -0,0 +1,12 @@ +{application, rabbit_snmp, + [{description, "Embedded SNMP Agent"}, + {vsn, "0.0.1"}, + {modules, [ + rabbit_snmp, + rabbit_snmp_sup, + rabbit_snmp_worker + ]}, + {registered, []}, + {mod, {rabbit_snmp, []}}, + {env, []}, + {applications, [kernel, stdlib, rabbit]}]}. diff --git a/include/records.hrl b/include/records.hrl new file mode 100644 index 0000000..f274a9f --- /dev/null +++ b/include/records.hrl @@ -0,0 +1 @@ +-record(rabbit_snmp_queue, {index, name, vhost, messages}). diff --git a/snmp/.index b/snmp/.index new file mode 100644 index 0000000..71829fe --- /dev/null +++ b/snmp/.index @@ -0,0 +1 @@ +RABBITMQ-MIB RABBITMQ-MIB.mib diff --git a/snmp/RABBITMQ-MIB.funcs b/snmp/RABBITMQ-MIB.funcs new file mode 100644 index 0000000..41178f5 --- /dev/null +++ b/snmp/RABBITMQ-MIB.funcs @@ -0,0 +1,3 @@ +{vhostTable, {snmp_generic, table_func, [vhostTable]}}. +{queueTable, {snmp_generic, table_func, [queueTable]}}. +{exchangeTable, {snmp_generic, table_func, [exchangeTable]}}. diff --git a/snmp/RABBITMQ-MIB.mib b/snmp/RABBITMQ-MIB.mib new file mode 100644 index 0000000..7e0f6aa --- /dev/null +++ b/snmp/RABBITMQ-MIB.mib @@ -0,0 +1,238 @@ +RABBITMQ-MIB DEFINITIONS ::= BEGIN + +-- +-- Top-level infrastructure of the Epic Ads enterprise MIB tree +-- + +IMPORTS + MODULE-IDENTITY, OBJECT-TYPE, Gauge32, Counter64, enterprises FROM SNMPv2-SMI + + OBJECT-GROUP FROM SNMPv2-CONF + + DisplayString, TruthValue FROM SNMPv2-TC; + + rabbitMQ MODULE-IDENTITY + LAST-UPDATED "200911040000Z" + ORGANIZATION "www.epicadvertising.com" + CONTACT-INFO + "e-mail: scott.brooks@epicadvertising.com" + DESCRIPTION + "RabbitMQ snmp mib" + REVISION "200911040000Z" + DESCRIPTION + "First draft" + ::= { enterprises 12346} + +rabbitGroups OBJECT IDENTIFIER ::= { rabbitMQ 1 } +vhosts OBJECT IDENTIFIER ::= { rabbitMQ 2 } +queues OBJECT IDENTIFIER ::= { rabbitMQ 3 } +exchanges OBJECT IDENTIFIER ::= { rabbitMQ 4 } + +vhostTable OBJECT-TYPE + SYNTAX SEQUENCE OF VhostEntry + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION "list of vhosts" + ::= { vhosts 1 } + +vhostTableEntry OBJECT-TYPE + SYNTAX VhostEntry + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION "vhost entry" + INDEX { vhostName } + ::= { vhostTable 1 } + +VhostEntry ::= SEQUENCE { + vhostName DisplayString +} + +vhostName OBJECT-TYPE + SYNTAX DisplayString + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Vhost name" + ::= { vhostTableEntry 1 } + +queueTable OBJECT-TYPE + SYNTAX SEQUENCE OF QueueStatisticsEntry + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION "A list of all the queues for a specific vhost" + ::= { queues 1 } + +queueTableEntry OBJECT-TYPE + SYNTAX QueueStatisticsEntry + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION "A queue" + INDEX { queueVhost, queueName } + ::= { queueTable 1 } + +QueueStatisticsEntry ::= SEQUENCE { + queueVhost DisplayString, + queueName DisplayString, + queueDurable TruthValue, + queueAutoDelete TruthValue, + queueMessages Gauge32, + queueUnAcknowledged Gauge32, + queueUnCommitted Gauge32, + queueReady Gauge32, + queueAcksUncommitted Gauge32, + queueConsumers Gauge32, + queueTransactions Gauge32, + queueMemory Counter64 +} + +queueVhost OBJECT-TYPE + SYNTAX DisplayString + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Queue Vhost" + ::= { queueTableEntry 1 } + +queueName OBJECT-TYPE + SYNTAX DisplayString + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Queue name" + ::= { queueTableEntry 2 } + +queueDurable OBJECT-TYPE + SYNTAX TruthValue + MAX-ACCESS read-only + STATUS current + DESCRIPTION "True if the queue is durable" + ::= { queueTableEntry 3 } + +queueAutoDelete OBJECT-TYPE + SYNTAX TruthValue + MAX-ACCESS read-only + STATUS current + DESCRIPTION "True if the queue is set to auto_delete" + ::= { queueTableEntry 4 } + +queueMessages OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Number of messages" + ::= { queueTableEntry 5 } + +queueUnAcknowledged OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Number of unacknowledged messages" + ::= { queueTableEntry 6 } + +queueUnCommitted OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Number of uncommitted messages" + ::= { queueTableEntry 7 } + +queueReady OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Number of ready messages" + ::= { queueTableEntry 8 } + +queueAcksUncommitted OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Number of uncommitted acks" + ::= { queueTableEntry 9 } + +queueConsumers OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Number of consumers" + ::= { queueTableEntry 10 } + +queueTransactions OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Number of transactions" + ::= { queueTableEntry 11 } + +queueMemory OBJECT-TYPE + SYNTAX Counter64 + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Amount of memory used" + ::= { queueTableEntry 12 } + +exchangeTable OBJECT-TYPE + SYNTAX SEQUENCE OF ExchangeEntry + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION "list of exchanges" + ::= { exchanges 1 } + +exchangeTableEntry OBJECT-TYPE + SYNTAX ExchangeEntry + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION "exchange entry" + INDEX { exchangeVhost, exchangeName } + ::= { exchangeTable 1 } + +ExchangeEntry ::= SEQUENCE { + exchangeVhost DisplayString, + exchangeName DisplayString, + exchangeType DisplayString, + exchangeDurable TruthValue, + exchangeAutoDelete TruthValue +} + +exchangeVhost OBJECT-TYPE + SYNTAX DisplayString + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Exchange Vhost" + ::= { exchangeTableEntry 1 } + +exchangeName OBJECT-TYPE + SYNTAX DisplayString + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Exchange name" + ::= { exchangeTableEntry 2 } + +exchangeType OBJECT-TYPE + SYNTAX DisplayString + MAX-ACCESS read-only + STATUS current + DESCRIPTION "Exchange Type" + ::= { exchangeTableEntry 3 } + +exchangeDurable OBJECT-TYPE + SYNTAX TruthValue + MAX-ACCESS read-only + STATUS current + DESCRIPTION "True if the queue is set to durable" + ::= { exchangeTableEntry 4 } + +exchangeAutoDelete OBJECT-TYPE + SYNTAX TruthValue + MAX-ACCESS read-only + STATUS current + DESCRIPTION "True if the queue is set to auto_delete" + ::= { exchangeTableEntry 5 } + + +rabbitGroup OBJECT-GROUP + OBJECTS { + queueVhost, queueName, queueDurable, queueAutoDelete, queueMessages, queueUnAcknowledged, queueUnCommitted, queueReady, queueAcksUncommitted, queueConsumers, queueTransactions, queueMemory, vhostName, exchangeVhost, exchangeType, exchangeName, exchangeDurable, exchangeAutoDelete + } + STATUS current + DESCRIPTION "Groups" + ::= { rabbitGroups 1 } + +END diff --git a/snmp/agent/conf/agent.conf b/snmp/agent/conf/agent.conf new file mode 100644 index 0000000..8167934 --- /dev/null +++ b/snmp/agent/conf/agent.conf @@ -0,0 +1,20 @@ +%% This file was generated by snmp_config (version-4.13.1) 2009-06-10 10:12:05 +%% This file defines the Agent local configuration info +%% The data is inserted into the snmpEngine* variables defined +%% in SNMP-FRAMEWORK-MIB, and the intAgent* variables defined +%% in OTP-SNMPEA-MIB. +%% Each row is a 2-tuple: +%% {AgentVariable, Value}. +%% For example +%% {intAgentUDPPort, 4000}. +%% The ip address for the agent is sent as id in traps. +%% {intAgentIpAddress, [127,42,17,5]}. +%% {snmpEngineID, "agentEngine"}. +%% {snmpEngineMaxMessageSize, 484}. +%% + + +{intAgentUDPPort, 4001}. +{intAgentIpAddress, [127,0,0,1]}. +{snmpEngineID, "RabbitMQ Stats"}. +{snmpEngineMaxMessageSize, 484}. diff --git a/snmp/agent/conf/community.conf b/snmp/agent/conf/community.conf new file mode 100644 index 0000000..5a64df6 --- /dev/null +++ b/snmp/agent/conf/community.conf @@ -0,0 +1 @@ +{"public", "public", "initial", "", ""}. diff --git a/snmp/agent/conf/context.conf b/snmp/agent/conf/context.conf new file mode 100644 index 0000000..8f15d54 --- /dev/null +++ b/snmp/agent/conf/context.conf @@ -0,0 +1,4 @@ +%% This file was automatically generated by snmp_config v4.13.1 2009-06-15 19:22:50 + +%% The default context +"". diff --git a/snmp/agent/conf/standard.conf b/snmp/agent/conf/standard.conf new file mode 100644 index 0000000..5425ab6 --- /dev/null +++ b/snmp/agent/conf/standard.conf @@ -0,0 +1,22 @@ +%% This file was generated by snmp_config (version-4.13.1) 2009-06-10 10:12:05 +%% This file defines the STANDARD-MIB info. +%% Each row is a 2-tuple: +%% {StandardVariable, Value}. +%% For example +%% {sysDescr, "Erlang SNMP agent"}. +%% {sysObjectID, [1,2,3]}. +%% {sysContact, "{mbj,eklas}@erlang.ericsson.se"}. +%% {sysName, "test"}. +%% {sysLocation, "erlang"}. +%% {sysServices, 72}. +%% {snmpEnableAuthenTraps, enabled}. +%% + + +{sysDescr, "RabbitMQ Stats"}. +{sysObjectID, [1,3,6,1,4,1,12346,1]}. +{sysContact, "sample@example.com"}. +{sysLocation, "Location"}. +{sysServices, 72}. +{snmpEnableAuthenTraps, enabled}. +{sysName, "rabbitmq"}. diff --git a/snmp/agent/conf/usm.conf b/snmp/agent/conf/usm.conf new file mode 100644 index 0000000..e69de29 diff --git a/snmp/agent/conf/vacm.conf b/snmp/agent/conf/vacm.conf new file mode 100644 index 0000000..18bdb3c --- /dev/null +++ b/snmp/agent/conf/vacm.conf @@ -0,0 +1,30 @@ +%% This file was generated by snmp_config (version-4.13.1) 2009-06-10 10:12:05 +%% This file defines the Mib Views. +%% The data is inserted into the vacm* tables defined +%% in SNMP-VIEW-BASED-ACM-MIB. +%% Each row is one of 3 tuples; one for each table in the MIB: +%% {vacmSecurityToGroup, SecModel, SecName, GroupName}. +%% {vacmAccess, GroupName, Prefix, SecModel, SecLevel, Match, RV, WV, NV}. +%% {vacmViewTreeFamily, ViewIndex, ViewSubtree, ViewStatus, ViewMask}. +%% For example +%% {vacmSecurityToGroup, v2c, "initial", "initial"}. +%% {vacmSecurityToGroup, usm, "initial", "initial"}. +%% read/notify access to system +%% {vacmAccess, "initial", "", any, noAuthNoPriv, exact, +%% "system", "", "system"}. +%% {vacmViewTreeFamily, "system", [1,3,6,1,2,1,1], included, null}. +%% {vacmViewTreeFamily, "exmib", [1,3,6,1,3], included, null}. % for EX1-MIB +%% {vacmViewTreeFamily, "internet", [1,3,6,1], included, null}. +%% + + +{vacmSecurityToGroup, v2c, "initial", "initial"}. +{vacmSecurityToGroup, v2c, "all-rights", "all-rights"}. +{vacmSecurityToGroup, v1, "initial", "initial"}. +{vacmSecurityToGroup, v1, "all-rights", "all-rights"}. +{vacmAccess, "initial", "", any, noAuthNoPriv, exact, "restricted", "", "restricted"}. +{vacmAccess, "initial", "", usm, authNoPriv, exact, "internet", "internet", "internet"}. +{vacmAccess, "initial", "", usm, authPriv, exact, "internet", "internet", "internet"}. +{vacmAccess, "all-rights", "", any, noAuthNoPriv, exact, "internet", "internet", "internet"}. +{vacmViewTreeFamily, "restricted", [1,3,6,1], included, null}. +{vacmViewTreeFamily, "internet", [1,3,6,1], included, null}. diff --git a/src/rabbit_snmp.erl b/src/rabbit_snmp.erl new file mode 100644 index 0000000..948632c --- /dev/null +++ b/src/rabbit_snmp.erl @@ -0,0 +1,34 @@ +-module(rabbit_snmp). + +-export([start/0, stop/0, start/2, stop/1]). + +-include("RABBITMQ-MIB.hrl"). + +load_snmp_environment() -> + Path = code:lib_dir(rabbitmq,snmp), + + ok = application:load(snmp), + {ok, Agent} = application:get_env(snmp, agent), + Config = proplists:get_value(config, Agent), + NewConfig = lists:keystore(dir, 1, Config, {dir, Path ++ "/agent/conf"}), + NewAgent = lists:keystore(db_dir, 1, (lists:keystore(config, 1, Agent, {config, NewConfig})), {db_dir, Path ++ "/agent/db"}), + application:set_env(snmp, agent, NewAgent), + + ok = application:start(snmp), + ok = snmpa:load_mibs(snmp_master_agent, [Path ++ "/RABBITMQ-MIB"]), + ok. + +start() -> + load_snmp_environment(), + rabbit_snmp_sup:start_link(), + ok. + +stop() -> + ok. + +start(normal, []) -> + load_snmp_environment(), + rabbit_snmp_sup:start_link(). + +stop(_State) -> + ok. diff --git a/src/rabbit_snmp_sup.erl b/src/rabbit_snmp_sup.erl new file mode 100644 index 0000000..232a561 --- /dev/null +++ b/src/rabbit_snmp_sup.erl @@ -0,0 +1,17 @@ +-module(rabbit_snmp_sup). +-behaviour(supervisor). + +-export([start_link/0, init/1]). + +start_link() -> + supervisor:start_link({local, ?MODULE}, ?MODULE, _Arg = []). + +init([]) -> + {ok, {{one_for_one, 3, 10}, + [{rabbit_snmp_worker, + {rabbit_snmp_worker, start_link, []}, + permanent, + 10000, + worker, + [rabbit_snmp_worker]} + ]}}. diff --git a/src/rabbit_snmp_worker.erl b/src/rabbit_snmp_worker.erl new file mode 100644 index 0000000..bf40a43 --- /dev/null +++ b/src/rabbit_snmp_worker.erl @@ -0,0 +1,108 @@ +-module(rabbit_snmp_worker). +-behaviour(gen_server). + +-export([start/0, start/2, stop/0, stop/1, start_link/0]). +-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). + + +-record(state, {update_interval}). + +start() -> + start_link(), + ok. + +start(normal, []) -> + start_link(). + +stop() -> + ok. + +stop(_State) -> + stop(). + +start_link() -> + gen_server:start_link({global, ?MODULE}, ?MODULE, [], []). + +init([]) -> + application:start(snmp), + io:format("Started snmp state poller~n", []), + UpdateInterval = 10000, + erlang:send_after(1, self(), update_stats), + {ok, #state{update_interval = UpdateInterval}}. + +create_exchange_row([]) -> + ok; +create_exchange_row([Row|Rest]) -> + {exchange, {resource, Vhost, exchange, ExchangeName}, ExchangeType, ExchangeDurability, ExchangeAutoDelete, _Args} = Row, + ListVhost = binary_to_list(Vhost), + ListExchange = binary_to_list(ExchangeName), + + SnmpRow = {ListVhost, ListExchange, + atom_to_list(ExchangeType), + ExchangeDurability, + ExchangeAutoDelete + }, + snmpa_local_db:table_create_row(exchangeTable, ListVhost ++ ListExchange, SnmpRow), + create_exchange_row(Rest). + +create_vhost_row([]) -> + ok; +create_vhost_row([Row|Rest]) -> + SnmpRow = {binary_to_list(Row)}, + snmpa_local_db:table_create_row(vhostTable, binary_to_list(Row), SnmpRow), + create_vhost_row(Rest). + +create_queue_row([]) -> + ok; +create_queue_row([Row|Rest]) -> + {resource, Vhost, queue, QueueName} = proplists:get_value(name, Row), + ListVhost = binary_to_list(Vhost), + ListQueue = binary_to_list(QueueName), + + SnmpRow = {ListVhost, ListQueue, + proplists:get_value(durable, Row), + proplists:get_value(auto_delete, Row), + proplists:get_value(messages, Row), + proplists:get_value(messages_unacknowledged, Row), + proplists:get_value(messages_uncommitted, Row), + proplists:get_value(messages_ready, Row), + proplists:get_value(acks_uncommitted, Row), + proplists:get_value(consumers, Row), + proplists:get_value(transactions, Row), + proplists:get_value(memory, Row) + }, + + snmpa_local_db:table_create_row(queueTable, ListVhost ++ ListQueue, SnmpRow), + create_queue_row(Rest). + + +update_stats() -> + Vhosts = rabbit_access_control:list_vhosts(), + create_vhost_row(Vhosts), + Queues = lists:append([rabbit_amqqueue:info_all(X) || X <- Vhosts]), + create_queue_row(Queues), + Exchanges = lists:append([rabbit_exchange:list(X) || X <- Vhosts]), + create_exchange_row(Exchanges), + ok. + +handle_call(_Msg,_From,State) -> + {reply, unknown_command, State}. + +handle_cast(_,State) -> + {noreply, State}. + +handle_info(update_stats, State) -> + update_stats(), + erlang:send_after(State#state.update_interval, self(), update_stats), + {noreply, State}; + +handle_info(Info, State) -> + io:format("Info: ~p~nState: ~p~n", [Info, State]), + {noreply, State}. + +terminate(_,_State) -> + ok. + +code_change(_OldVsn, State, _Extra) -> + {ok, State}. +
bjeanes/twibblr
38dec03a46735db1d508a3fcb7470f4c0a070eba
Preview correctly using any markdown library it can find and parsing it, as well as caching output in Post#html_body in the DB
diff --git a/app/views/layouts/twibblr.html.erb b/app/views/layouts/twibblr.html.erb index 28612fb..f56ec33 100644 --- a/app/views/layouts/twibblr.html.erb +++ b/app/views/layouts/twibblr.html.erb @@ -1,47 +1,47 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title><%= site_name %> - powered by Twibblr</title> <meta name="keywords" content="" /> <meta name="description" content="" /> <link href="/twibblr/stylesheets/master.css" rel="stylesheet" type="text/css" media="screen" /> - <%= javascript_include_tag 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js' %> + <%= javascript_include_tag 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js', 'http://plugins.jquery.com/files/jquery.timer.js_0.txt' %>s <%= yield :head %> </head> <body> <!-- start header --> <div id="header"> <div id="logo"> <h1><%= link_to site_name, "/" %></h1> <p>Powered by <a href="http://github.com/bjeanes/twibblr">Twibblr</a></p> </div> <div id="search"> <form method="get" action=""> <fieldset> <input id="s" type="text" name="s" value="" /> <input id="x" type="submit" value="Search" /> </fieldset> </form> </div> </div> <!-- end header --> <!-- start page --> <div id="page"> <!-- start content --> <div id="content"> <%= yield %> </div> <!-- end content --> <!-- start sidebar --> <%= render :partial => 'layouts/sidebar' %> <!-- end sidebar --> </div> <!-- end page --> <div id="footer"> <p>&copy;2007 All Rights Reserved. &nbsp;&bull;&nbsp; Design by <a href="http://templatefusion.org">TemplateFusion</a> &nbsp;&bull;&nbsp; Icons by <a href="http://www.famfamfam.com/">FAMFAMFAM</a>.</p> </div> </body> </html> \ No newline at end of file diff --git a/app/views/layouts/twibblr_admin.html.erb b/app/views/layouts/twibblr_admin.html.erb index 342f167..02873f3 100644 --- a/app/views/layouts/twibblr_admin.html.erb +++ b/app/views/layouts/twibblr_admin.html.erb @@ -1,18 +1,18 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title><%= site_name %> Admin</title> <link href="/twibblr/stylesheets/admin.css" rel="stylesheet" type="text/css" media="screen" /> - <%= javascript_include_tag 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js' %> + <%= javascript_include_tag 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js', 'http://plugins.jquery.com/files/jquery.timer.js_0.txt' %> </head> <body> <%= yield %> </body> </html> diff --git a/app/views/twibblr/admin/posts/_preview.html.erb b/app/views/twibblr/admin/posts/_preview.html.erb index ec2ef5b..97e23ea 100644 --- a/app/views/twibblr/admin/posts/_preview.html.erb +++ b/app/views/twibblr/admin/posts/_preview.html.erb @@ -1,9 +1,9 @@ <div class="preview post"> - <h1><%= @post.title %></h1> + <h1><%= @post.title.blank? ? "Untitled" : @post.title %></h1> <div class="body"> <%= @post.html_body %> </div> </div> diff --git a/app/views/twibblr/admin/posts/new.html.erb b/app/views/twibblr/admin/posts/new.html.erb index 8a25b6c..92bc3af 100644 --- a/app/views/twibblr/admin/posts/new.html.erb +++ b/app/views/twibblr/admin/posts/new.html.erb @@ -1,25 +1,33 @@ <% form_for :post, @post, :url => admin_posts_path, :html => {:id => "admin_new_post_form"} do |f| %> <%= error_messages_for :post %> <p> <%= f.label :title %> <br /> <%= f.text_field :title %> </p> <p> <%= f.label :body %> <br /> <%= f.text_area :body %> </p> <%= f.submit "Create" %> <% end %> <div id="preview"> - + <%= render :partial => 'twibblr/admin/posts/preview' %> </div> <script type="text/javascript" charset="utf-8"> - $('#post_body').keypress(function(){ - $('#preview').load("<%= preview_admin_posts_path %>", $('#admin_new_post_form').serializeArray()); + var update = false; + + $('#post_body, #post_title').keypress(function(){ + update = true; + }); + + $.timer(1000, function(timer) { + if(update) { + $('#preview').load("<%= preview_admin_posts_path %>", $('#admin_new_post_form').serializeArray()); + } }); </script> \ No newline at end of file diff --git a/app/views/twibblr/posts/_post.html.erb b/app/views/twibblr/posts/_post.html.erb index 7857b27..0de67ff 100644 --- a/app/views/twibblr/posts/_post.html.erb +++ b/app/views/twibblr/posts/_post.html.erb @@ -1,17 +1,17 @@ <div class="post"> <h1 class="title"><%= link_to post.title.titleize, post.link %></h1> <p class="byline"> <small> Posted on <%= post.created_at.strftime("%B %d, %Y") %> | <%= link_to "Edit post", edit_admin_post_path(post) %> </small> </p> <div class="entry"> <% if controller.action_name == "show" %> - <%= simple_format(post.body) %> + <%= post.html_body %> <% else %> <%= truncate(simple_format(post.body), 250, ' ... (continued)') %> <% end %> </div> <p class="meta"><%= link_to "Read more", post.link, :class => 'more' %> &nbsp;&nbsp;&nbsp; <a href="#" class="comments">Comments (1337)</a></p> </div> \ No newline at end of file diff --git a/lib/twibblr.rb b/lib/twibblr.rb index 3ae1f6b..ee268de 100644 --- a/lib/twibblr.rb +++ b/lib/twibblr.rb @@ -1,30 +1,52 @@ module ::Twibblr begin Config = YAML.load_file(File.join(RAILS_ROOT, 'config', 'twibblr.yml')) rescue Errno::ENOENT => e abort "Please run `rake twibblr:install` to setup the necessary files for Twibblr" end - def self.renderer - empty = Class.new do - attr_accessor :to_html - def initialize(body); self.to_html = "!!! #{body} !!!"; end + class ReturnRenderer + attr_accessor :to_html + def initialize(body) + self.to_html = "!!! #{body} !!!" end + end - @@renderer ||= begin - case Config['renderer'] - when 'markdown' - empty - when 'textile' - require 'RedCloth' - RedCloth - when nil then empty - else raise "Unknown renderer" - end - end + + def self.renderer + @@renderer ||= load_renderer end def self.root Plugin.directory end + + protected + + def self.load_renderer + case r = Config['renderer'] + when 'markdown', :markdown + %w{Maruku RDiscount BlueCloth PEGMarkdown/peg_mardown}.each do |lib| + begin + require lib.downcase + return lib.constantize + rescue MissingSourceFile + end + end + when 'textile', :textile + require 'RedCloth' + return RedCloth + when nil then return ReturnRenderer + else + begin + require r.to_s + return r.camelize.constantize + rescue MissingSourceFile # do nothing, exception raised below + rescue NameError + raise "Found renderer #{r} but could not determine class name (tried #{r.camelize.constantize})" + end + end + + raise "No such renderer: #{r}" + end end \ No newline at end of file
bjeanes/twibblr
e8e0c9761617da8ef2b536764322818f9c734eb2
Hacky post preview going
diff --git a/app/controllers/twibblr/admin/posts_controller.rb b/app/controllers/twibblr/admin/posts_controller.rb index fed5cfa..ff1cd15 100644 --- a/app/controllers/twibblr/admin/posts_controller.rb +++ b/app/controllers/twibblr/admin/posts_controller.rb @@ -1,40 +1,44 @@ module Twibblr module Admin class PostsController < AdminController def index @posts = Post.all end def new @post = Post.new end def create @post = Post.new(params[:post]) if @post.save flash[:notice] = "You have created the post '#{@post.title}'" redirect_to :action => :index else render :new end end def edit @post = Post.find(params[:id]) end def update @post = Post.find(params[:id]) if @post.update_attributes(params[:post]) flash[:notice] = "You have updated the post '#{@post.title}'" redirect_to :action => :index else render :edit end end + def preview + @post = Post.new(params[:post]) + render :partial => 'preview', :layout => false + end end end end \ No newline at end of file diff --git a/app/models/twibblr/post.rb b/app/models/twibblr/post.rb index c94301b..3436da7 100644 --- a/app/models/twibblr/post.rb +++ b/app/models/twibblr/post.rb @@ -1,58 +1,64 @@ class Twibblr::Post < ActiveRecord::Base set_table_name :twibblr_posts default_scope :order => "created_at DESC" has_many :comments, :order => "created_at ASC" has_many :posts_tags has_many :tags, :through => :posts_tags, :order => "name ASC" named_scope :archive, :group => "month(created_at)" validates_presence_of :body, :title before_save :cache_body_as_html + + delegate :renderer, :to => Twibblr %w{year month day}.each do |time| delegate time, :to => :created_at named_scope :"in_#{time}", lambda { |num| {:conditions => ["#{time.upcase}(created_at) = ?", num] } } end def date created_at.to_date.to_s(:long_ordinal) end def to_s title end def link @link ||= "/#{created_at.year}/#{created_at.month}/#{created_at.day}/#{to_param}" end def to_param if title.blank? id else "#{id}-#{title.parameterize}" end end + def html_body + self[:html_body] ||= render_html_body + end + protected ############################################################################## def cache_body_as_html self.html_body = render_html_body end # This is a bit of a no-no but it # means the markdown/textile generation # only has to be done on save and not # on every page load. # TODO: replace this with fragment caching # later... def render_html_body # FIXME actually render the text renderer.new(body).to_html end end \ No newline at end of file diff --git a/app/views/layouts/twibblr.html.erb b/app/views/layouts/twibblr.html.erb index fd09d42..28612fb 100644 --- a/app/views/layouts/twibblr.html.erb +++ b/app/views/layouts/twibblr.html.erb @@ -1,46 +1,47 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title><%= site_name %> - powered by Twibblr</title> <meta name="keywords" content="" /> <meta name="description" content="" /> <link href="/twibblr/stylesheets/master.css" rel="stylesheet" type="text/css" media="screen" /> + <%= javascript_include_tag 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js' %> <%= yield :head %> </head> <body> <!-- start header --> <div id="header"> <div id="logo"> <h1><%= link_to site_name, "/" %></h1> <p>Powered by <a href="http://github.com/bjeanes/twibblr">Twibblr</a></p> </div> <div id="search"> <form method="get" action=""> <fieldset> <input id="s" type="text" name="s" value="" /> <input id="x" type="submit" value="Search" /> </fieldset> </form> </div> </div> <!-- end header --> <!-- start page --> <div id="page"> <!-- start content --> <div id="content"> <%= yield %> </div> <!-- end content --> <!-- start sidebar --> <%= render :partial => 'layouts/sidebar' %> <!-- end sidebar --> </div> <!-- end page --> <div id="footer"> <p>&copy;2007 All Rights Reserved. &nbsp;&bull;&nbsp; Design by <a href="http://templatefusion.org">TemplateFusion</a> &nbsp;&bull;&nbsp; Icons by <a href="http://www.famfamfam.com/">FAMFAMFAM</a>.</p> </div> </body> </html> \ No newline at end of file diff --git a/app/views/layouts/twibblr_admin.html.erb b/app/views/layouts/twibblr_admin.html.erb index 43c158b..342f167 100644 --- a/app/views/layouts/twibblr_admin.html.erb +++ b/app/views/layouts/twibblr_admin.html.erb @@ -1,16 +1,18 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title><%= site_name %> Admin</title> + <link href="/twibblr/stylesheets/admin.css" rel="stylesheet" type="text/css" media="screen" /> + <%= javascript_include_tag 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js' %> </head> <body> <%= yield %> </body> </html> diff --git a/app/views/twibblr/admin/posts/_preview.html.erb b/app/views/twibblr/admin/posts/_preview.html.erb new file mode 100644 index 0000000..ec2ef5b --- /dev/null +++ b/app/views/twibblr/admin/posts/_preview.html.erb @@ -0,0 +1,9 @@ +<div class="preview post"> + <h1><%= @post.title %></h1> + <div class="body"> + <%= @post.html_body %> + </div> +</div> + + + diff --git a/app/views/twibblr/admin/posts/new.html.erb b/app/views/twibblr/admin/posts/new.html.erb index fab87ff..8a25b6c 100644 --- a/app/views/twibblr/admin/posts/new.html.erb +++ b/app/views/twibblr/admin/posts/new.html.erb @@ -1,15 +1,25 @@ -<% form_for :post, @post, :url => admin_posts_path do |f| %> +<% form_for :post, @post, :url => admin_posts_path, :html => {:id => "admin_new_post_form"} do |f| %> <%= error_messages_for :post %> <p> <%= f.label :title %> <br /> <%= f.text_field :title %> </p> <p> <%= f.label :body %> <br /> <%= f.text_area :body %> </p> <%= f.submit "Create" %> -<% end %> \ No newline at end of file +<% end %> + +<div id="preview"> + +</div> + +<script type="text/javascript" charset="utf-8"> + $('#post_body').keypress(function(){ + $('#preview').load("<%= preview_admin_posts_path %>", $('#admin_new_post_form').serializeArray()); + }); +</script> \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 827a18b..fc48585 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,33 +1,33 @@ YEAR_REGEX = /\d{4}/ MONTH_REGEX = /(?:0?[1-9]|1[012])/ DAY_REGEX = /(?:0?[1-9]|[12][0-9]|3[01])/ PARAM_REGEX = /\d+(?:-[a-z0-9_-]+?)?/ ActionController::Routing::Routes.draw do |map| map.with_options :conditions => {:method => :get} do |get| get.with_options :controller => "twibblr/posts" do |posts| posts.with_options :action => "index" do |list_posts| list_posts.root list_posts.posts "/posts.:format" list_posts.map "/:year.:format", :requirements => {:year => YEAR_REGEX} list_posts.map "/:year/:month.:format", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX} list_posts.map "/:year/:month/:day.:format", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX, :day => DAY_REGEX} end posts.map "/tags/:tag", :action => "by_tag" options = {:action => "show", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX, :day => DAY_REGEX, :id => PARAM_REGEX}} posts.post "/:year/:month/:day/:id", options posts.post "/posts/:id", :action => "show" posts.formatted_post "/:year/:month/:day/:id.:format", options end end map.namespace :admin, :namespace => "twibblr/" do |admin| admin.root :controller => 'admin', :action => 'index' - admin.resources :posts + admin.resources :posts, :collection => {:preview => :post} admin.resources :tags end end \ No newline at end of file diff --git a/lib/twibblr.rb b/lib/twibblr.rb index 3643aa8..3ae1f6b 100644 --- a/lib/twibblr.rb +++ b/lib/twibblr.rb @@ -1,25 +1,30 @@ module ::Twibblr begin Config = YAML.load_file(File.join(RAILS_ROOT, 'config', 'twibblr.yml')) rescue Errno::ENOENT => e abort "Please run `rake twibblr:install` to setup the necessary files for Twibblr" end def self.renderer + empty = Class.new do + attr_accessor :to_html + def initialize(body); self.to_html = "!!! #{body} !!!"; end + end + @@renderer ||= begin case Config['renderer'] when 'markdown' - # TODO require different markdown libraries until one provides Markdown constant - const_set '::Markdown', Class.new { def initialize(*args);end; def to_html; ''; end; } + empty when 'textile' require 'RedCloth' RedCloth + when nil then empty else raise "Unknown renderer" end end end def self.root Plugin.directory end end \ No newline at end of file diff --git a/public/stylesheets/admin.css b/public/stylesheets/admin.css new file mode 100644 index 0000000..6d9e4f3 --- /dev/null +++ b/public/stylesheets/admin.css @@ -0,0 +1,4 @@ +body { + background-color: #2E2E2E; + color: #B19557; +} \ No newline at end of file
bjeanes/twibblr
acd20fd8314cead6fb73586bb2c468c16f9934e5
A few architechtural changes
diff --git a/app/controllers/twibblr/admin/admin_controller.rb b/app/controllers/twibblr/admin/admin_controller.rb index 34248ff..c9ce734 100644 --- a/app/controllers/twibblr/admin/admin_controller.rb +++ b/app/controllers/twibblr/admin/admin_controller.rb @@ -1,20 +1,20 @@ module Twibblr module Admin class AdminController < ::Twibblr::BaseController before_filter :log_in_required layout 'twibblr_admin' def index end protected def log_in_required authenticate_or_request_with_http_basic do |login, password| - login == CONFIG['username'].to_s && password == CONFIG['password'].to_s + login == Config['username'].to_s && password == Config['password'].to_s end end end end end \ No newline at end of file diff --git a/app/controllers/twibblr/base_controller.rb b/app/controllers/twibblr/base_controller.rb index e175d01..ee6581b 100644 --- a/app/controllers/twibblr/base_controller.rb +++ b/app/controllers/twibblr/base_controller.rb @@ -1,18 +1,18 @@ # Define a master controller for plugin to have defaults set everywhere module Twibblr class BaseController < ::ApplicationController helper 'twibblr/main' filter_parameter_logging :password layout :choose_layout protected def development? RAILS_ENV == "development" end def choose_layout - CONFIG['layout'] + Config['layout'] end end end \ No newline at end of file diff --git a/app/helpers/twibblr/main_helper.rb b/app/helpers/twibblr/main_helper.rb index 589d065..79cbd8b 100644 --- a/app/helpers/twibblr/main_helper.rb +++ b/app/helpers/twibblr/main_helper.rb @@ -1,49 +1,49 @@ module Twibblr::MainHelper def render_posts(*args, &block) # if they are fetching posts in the controller # then awesome(!) otherwise get it for them posts = @posts || Twibblr::Post # @posts can be Post from controller posts = posts.all(*args) if posts == Twibblr::Post if block_given? posts.each do |post| render_post(post, &block) end else render :partial => 'post', :collection => posts end end def render_tags(*args) raise "No Block Given" unless block_given? options = {:order => "name"}.merge(args.extract_options!) args << options (@tags || Tag.in_use.all(*args)).each {|tag| yield(tag)} end def site_name config['site_name'].titleize || 'My website' end def config - Twibblr::CONFIG + Twibblr::Config end private def render_post(post, &block) raise "No block given" unless block_given? case block.arity when 1 then yield(post) when 2 then yield(post.title, post.body) when 3 then yield(post.title, post.body, post.created_at) when 4 then yield(post.title, post.body, post.created_at, post.tags) when 5 then yield(post.title, post.body, post.created_at, post.tags, post.comments) else raise "Parameter Error" end end end \ No newline at end of file diff --git a/config/environment.rb b/config/environment.rb index c788731..a43e23c 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,15 +1,18 @@ # This ensures that helpers reload in development as well ActiveSupport::Dependencies.load_once_paths.clear if RAILS_ENV == "development" # Get the configuration object config = Rails.configuration # We can do gem dependencies like in Rails' evironment.rb # because load_gems is called twice, once before load_plugins # and once after to get plugin dependencies -config.gem "ultraviolet", :lib => "uv" +# config.gem "ultraviolet", :lib => "uv" +# config.gem "harsh" # Load plug-in initializers -Dir.chdir(File.join(Twibblr::ROOT, "config", "initializers")) do +# NOTE: This will get loaded BEFORE Rails' initializers, +# which don't even run if the gem checking fails +Dir.chdir(File.join(Twibblr.root, "config", "initializers")) do Dir["*.rb"].each { |file| load(file) } end \ No newline at end of file diff --git a/config/twibblr.yml.erb b/config/twibblr.yml.erb index fc3ff7b..955dfde 100644 --- a/config/twibblr.yml.erb +++ b/config/twibblr.yml.erb @@ -1,4 +1,5 @@ site_name: <%= File.basename(RAILS_ROOT) %> username: <%= `whoami`.chomp %> password: -layout: twibblr \ No newline at end of file +layout: twibblr +renderer: markdown \ No newline at end of file diff --git a/init.rb b/init.rb index 99f57b3..90f4f3c 100644 --- a/init.rb +++ b/init.rb @@ -1,13 +1,4 @@ require 'yaml' - -module ::Twibblr - begin - CONFIG = YAML.load_file(File.join(RAILS_ROOT, 'config', 'twibblr.yml')) - rescue Errno::ENOENT => e - abort "Please run `rake twibblr:install` to setup the necessary files for Twibblr" - end -end - -Twibblr::ROOT = self.directory - +require File.join(File.dirname(__FILE__), "lib", "twibblr") +Twibblr::Plugin = self require File.join(File.dirname(__FILE__), "config", "environment") \ No newline at end of file diff --git a/lib/twibblr.rb b/lib/twibblr.rb new file mode 100644 index 0000000..3643aa8 --- /dev/null +++ b/lib/twibblr.rb @@ -0,0 +1,25 @@ +module ::Twibblr + begin + Config = YAML.load_file(File.join(RAILS_ROOT, 'config', 'twibblr.yml')) + rescue Errno::ENOENT => e + abort "Please run `rake twibblr:install` to setup the necessary files for Twibblr" + end + + def self.renderer + @@renderer ||= begin + case Config['renderer'] + when 'markdown' + # TODO require different markdown libraries until one provides Markdown constant + const_set '::Markdown', Class.new { def initialize(*args);end; def to_html; ''; end; } + when 'textile' + require 'RedCloth' + RedCloth + else raise "Unknown renderer" + end + end + end + + def self.root + Plugin.directory + end +end \ No newline at end of file
bjeanes/twibblr
24e4a3482cda3d73efc84aef6800ed20be14fba4
Playing around with the idea of caching the HTML of the body to save on having to render the body to HTML on every request (though fragment caching could also work)
diff --git a/app/models/twibblr/post.rb b/app/models/twibblr/post.rb index cc346d2..c94301b 100644 --- a/app/models/twibblr/post.rb +++ b/app/models/twibblr/post.rb @@ -1,38 +1,58 @@ class Twibblr::Post < ActiveRecord::Base set_table_name :twibblr_posts default_scope :order => "created_at DESC" has_many :comments, :order => "created_at ASC" has_many :posts_tags has_many :tags, :through => :posts_tags, :order => "name ASC" named_scope :archive, :group => "month(created_at)" validates_presence_of :body, :title + + before_save :cache_body_as_html %w{year month day}.each do |time| delegate time, :to => :created_at named_scope :"in_#{time}", lambda { |num| {:conditions => ["#{time.upcase}(created_at) = ?", num] } } end def date created_at.to_date.to_s(:long_ordinal) end def to_s title end def link @link ||= "/#{created_at.year}/#{created_at.month}/#{created_at.day}/#{to_param}" end def to_param if title.blank? id else "#{id}-#{title.parameterize}" end end + + protected ############################################################################## + + def cache_body_as_html + self.html_body = render_html_body + end + + # This is a bit of a no-no but it + # means the markdown/textile generation + # only has to be done on save and not + # on every page load. + # TODO: replace this with fragment caching + # later... + def render_html_body + # FIXME actually render the text + renderer.new(body).to_html + end + end \ No newline at end of file diff --git a/db/migrate/20090410161154_add_html_body_to_posts.rb b/db/migrate/20090410161154_add_html_body_to_posts.rb new file mode 100644 index 0000000..514768b --- /dev/null +++ b/db/migrate/20090410161154_add_html_body_to_posts.rb @@ -0,0 +1,9 @@ +class AddHtmlBodyToPosts < ActiveRecord::Migration + def self.up + add_column :twibblr_posts, :html_body, :text + end + + def self.down + remove_column :twibblr_posts, :html_body + end +end
bjeanes/twibblr
bf6964174dd53d147c3309407db7c0b4db5fb31d
Get some gem dependencies working from within rails engine!
diff --git a/config/environment.rb b/config/environment.rb new file mode 100644 index 0000000..c788731 --- /dev/null +++ b/config/environment.rb @@ -0,0 +1,15 @@ +# This ensures that helpers reload in development as well +ActiveSupport::Dependencies.load_once_paths.clear if RAILS_ENV == "development" + +# Get the configuration object +config = Rails.configuration + +# We can do gem dependencies like in Rails' evironment.rb +# because load_gems is called twice, once before load_plugins +# and once after to get plugin dependencies +config.gem "ultraviolet", :lib => "uv" + +# Load plug-in initializers +Dir.chdir(File.join(Twibblr::ROOT, "config", "initializers")) do + Dir["*.rb"].each { |file| load(file) } +end \ No newline at end of file diff --git a/init.rb b/init.rb index 52d5c8b..99f57b3 100644 --- a/init.rb +++ b/init.rb @@ -1,19 +1,13 @@ require 'yaml' -# This ensures that helpers reload in development as well -ActiveSupport::Dependencies.load_once_paths.clear if RAILS_ENV == "development" - module ::Twibblr begin CONFIG = YAML.load_file(File.join(RAILS_ROOT, 'config', 'twibblr.yml')) rescue Errno::ENOENT => e abort "Please run `rake twibblr:install` to setup the necessary files for Twibblr" end end Twibblr::ROOT = self.directory -# Load plug-in initializers -Dir.chdir(File.join(Twibblr::ROOT, "config", "initializers")) do - Dir["*.rb"].each { |file| require file } -end \ No newline at end of file +require File.join(File.dirname(__FILE__), "config", "environment") \ No newline at end of file
bjeanes/twibblr
46695c163ea02e5e65057c5302003e0816471814
Fixed exception if you start server before running the install task
diff --git a/init.rb b/init.rb index 94235de..52d5c8b 100644 --- a/init.rb +++ b/init.rb @@ -1,15 +1,19 @@ require 'yaml' # This ensures that helpers reload in development as well ActiveSupport::Dependencies.load_once_paths.clear if RAILS_ENV == "development" module ::Twibblr - CONFIG = YAML.load_file(File.join(RAILS_ROOT, 'config', 'twibblr.yml')) + begin + CONFIG = YAML.load_file(File.join(RAILS_ROOT, 'config', 'twibblr.yml')) + rescue Errno::ENOENT => e + abort "Please run `rake twibblr:install` to setup the necessary files for Twibblr" + end end Twibblr::ROOT = self.directory # Load plug-in initializers Dir.chdir(File.join(Twibblr::ROOT, "config", "initializers")) do Dir["*.rb"].each { |file| require file } end \ No newline at end of file diff --git a/tasks/install.rake b/tasks/install.rake index d3d3e79..97bf5aa 100644 --- a/tasks/install.rake +++ b/tasks/install.rake @@ -1,9 +1,9 @@ namespace :twibblr do - task :install => [:environment] do + task :install do require File.join(File.dirname(__FILE__), '..', 'install') end task :uninstall do require File.join(File.dirname(__FILE__), '..', 'uninstall') end end
bjeanes/twibblr
2bd0bcc1ad6360b530653a47402f2ced57416a28
re-add initializers folder
diff --git a/config/initializers/.gitignore b/config/initializers/.gitignore new file mode 100644 index 0000000..e69de29
bjeanes/twibblr
b08a6d024ed7d8de15e3539829798ac84b11cb73
Edit posts, and only show tags in sidebar with more than one post in it
diff --git a/app/controllers/twibblr/admin/posts_controller.rb b/app/controllers/twibblr/admin/posts_controller.rb index 45477e0..fed5cfa 100644 --- a/app/controllers/twibblr/admin/posts_controller.rb +++ b/app/controllers/twibblr/admin/posts_controller.rb @@ -1,24 +1,40 @@ module Twibblr module Admin class PostsController < AdminController def index @posts = Post.all end def new @post = Post.new end def create @post = Post.new(params[:post]) if @post.save flash[:notice] = "You have created the post '#{@post.title}'" redirect_to :action => :index else render :new end end + + def edit + @post = Post.find(params[:id]) + end + + def update + @post = Post.find(params[:id]) + + if @post.update_attributes(params[:post]) + flash[:notice] = "You have updated the post '#{@post.title}'" + redirect_to :action => :index + else + render :edit + end + end + end end end \ No newline at end of file diff --git a/app/helpers/twibblr/main_helper.rb b/app/helpers/twibblr/main_helper.rb index 2d37cb1..589d065 100644 --- a/app/helpers/twibblr/main_helper.rb +++ b/app/helpers/twibblr/main_helper.rb @@ -1,46 +1,49 @@ module Twibblr::MainHelper def render_posts(*args, &block) # if they are fetching posts in the controller # then awesome(!) otherwise get it for them - posts = @posts || Post.all(*args) + posts = @posts || Twibblr::Post + + # @posts can be Post from controller + posts = posts.all(*args) if posts == Twibblr::Post if block_given? posts.each do |post| render_post(post, &block) end else render :partial => 'post', :collection => posts end end def render_tags(*args) raise "No Block Given" unless block_given? options = {:order => "name"}.merge(args.extract_options!) args << options - (@tags || Tag.all(*args)).each {|tag| yield(tag)} + (@tags || Tag.in_use.all(*args)).each {|tag| yield(tag)} end def site_name config['site_name'].titleize || 'My website' end def config Twibblr::CONFIG end private def render_post(post, &block) raise "No block given" unless block_given? case block.arity when 1 then yield(post) when 2 then yield(post.title, post.body) when 3 then yield(post.title, post.body, post.created_at) when 4 then yield(post.title, post.body, post.created_at, post.tags) when 5 then yield(post.title, post.body, post.created_at, post.tags, post.comments) else raise "Parameter Error" end end end \ No newline at end of file diff --git a/app/models/twibblr/tag.rb b/app/models/twibblr/tag.rb index 80b0311..0227b36 100644 --- a/app/models/twibblr/tag.rb +++ b/app/models/twibblr/tag.rb @@ -1,35 +1,37 @@ class Twibblr::Tag < ActiveRecord::Base set_table_name :twibblr_tags - default_scope :order => "posts_count", :conditions => ["posts_count > ?", 0] + default_scope :order => "posts_count" has_many :posts_tags has_many :posts, :through => :posts_tags, :order => "created_at ASC" + named_scope :in_use, :conditions => "posts_count > 0" + before_create :set_permalink before_save :lowercase_name def to_s name end def to_param permalink end def self.[](identifier) identifier.is_a?(Fixnum) ? find(identifier) : find(:first, :conditions => ["name = :name OR permalink = :name", {:name => identifier.to_s}]) rescue nil end private def set_permalink self.permalink = name.parameterize if permalink.blank? end def lowercase_name self.name.downcase! end end \ No newline at end of file diff --git a/app/views/twibblr/admin/posts/edit.html.erb b/app/views/twibblr/admin/posts/edit.html.erb new file mode 100644 index 0000000..20f8d3f --- /dev/null +++ b/app/views/twibblr/admin/posts/edit.html.erb @@ -0,0 +1,15 @@ +<% form_for :post, @post, :url => admin_post_path(@post), :html => {:method => :put} do |f| %> + <%= error_messages_for :post %> + <p> + <%= f.label :title %> + <br /> + <%= f.text_field :title %> + </p> + <p> + <%= f.label :body %> + <br /> + <%= f.text_area :body %> + </p> + + <%= f.submit "Update" %> +<% end %> \ No newline at end of file diff --git a/app/views/twibblr/posts/_post.html.erb b/app/views/twibblr/posts/_post.html.erb index fa913e4..7857b27 100644 --- a/app/views/twibblr/posts/_post.html.erb +++ b/app/views/twibblr/posts/_post.html.erb @@ -1,12 +1,17 @@ <div class="post"> <h1 class="title"><%= link_to post.title.titleize, post.link %></h1> - <p class="byline"><small>Posted on <%= post.created_at.strftime("%B %d, %Y") %> | <a href="#">Edit Post</a></small></p> + <p class="byline"> + <small> + Posted on <%= post.created_at.strftime("%B %d, %Y") %> | + <%= link_to "Edit post", edit_admin_post_path(post) %> + </small> + </p> <div class="entry"> <% if controller.action_name == "show" %> <%= simple_format(post.body) %> <% else %> <%= truncate(simple_format(post.body), 250, ' ... (continued)') %> <% end %> </div> - <p class="meta"><a href="#" class="more">Read More</a> &nbsp;&nbsp;&nbsp; <a href="#" class="comments">Comments (1337)</a></p> + <p class="meta"><%= link_to "Read more", post.link, :class => 'more' %> &nbsp;&nbsp;&nbsp; <a href="#" class="comments">Comments (1337)</a></p> </div> \ No newline at end of file diff --git a/app/views/twibblr/posts/show.html.erb b/app/views/twibblr/posts/show.html.erb index 42841f9..f63e9a5 100644 --- a/app/views/twibblr/posts/show.html.erb +++ b/app/views/twibblr/posts/show.html.erb @@ -1 +1 @@ -<%= render :partial => 'post', :collection => @post %> \ No newline at end of file +<%= render :partial => 'post', :locals => {:post => @post} %> \ No newline at end of file
bjeanes/twibblr
1ed3eab4c5969ad23ae7cbdf5ddf34f32da2a02f
Woah can create posts through admin interface and have them show up in site
diff --git a/app/controllers/twibblr/admin/posts_controller.rb b/app/controllers/twibblr/admin/posts_controller.rb index debc4f8..45477e0 100644 --- a/app/controllers/twibblr/admin/posts_controller.rb +++ b/app/controllers/twibblr/admin/posts_controller.rb @@ -1,6 +1,24 @@ module Twibblr module Admin class PostsController < AdminController + def index + @posts = Post.all + end + + def new + @post = Post.new + end + + def create + @post = Post.new(params[:post]) + + if @post.save + flash[:notice] = "You have created the post '#{@post.title}'" + redirect_to :action => :index + else + render :new + end + end end end end \ No newline at end of file diff --git a/app/helpers/twibblr/main_helper.rb b/app/helpers/twibblr/main_helper.rb index ed97df6..2d37cb1 100644 --- a/app/helpers/twibblr/main_helper.rb +++ b/app/helpers/twibblr/main_helper.rb @@ -1,46 +1,46 @@ module Twibblr::MainHelper def render_posts(*args, &block) # if they are fetching posts in the controller # then awesome(!) otherwise get it for them posts = @posts || Post.all(*args) if block_given? posts.each do |post| render_post(post, &block) end else - render :partial => posts + render :partial => 'post', :collection => posts end end def render_tags(*args) raise "No Block Given" unless block_given? options = {:order => "name"}.merge(args.extract_options!) args << options (@tags || Tag.all(*args)).each {|tag| yield(tag)} end def site_name config['site_name'].titleize || 'My website' end def config Twibblr::CONFIG end private def render_post(post, &block) raise "No block given" unless block_given? case block.arity when 1 then yield(post) when 2 then yield(post.title, post.body) when 3 then yield(post.title, post.body, post.created_at) when 4 then yield(post.title, post.body, post.created_at, post.tags) when 5 then yield(post.title, post.body, post.created_at, post.tags, post.comments) else raise "Parameter Error" end end end \ No newline at end of file diff --git a/app/views/twibblr/admin/posts/index.html.erb b/app/views/twibblr/admin/posts/index.html.erb index 09af61c..0382592 100644 --- a/app/views/twibblr/admin/posts/index.html.erb +++ b/app/views/twibblr/admin/posts/index.html.erb @@ -1 +1,7 @@ -Show posts here \ No newline at end of file +<ul> + <% @posts.each do |post| %> + <li><%= link_to post.title, post_path(post) %> (<%= link_to "Edit", edit_admin_post_path(post) %>)</li> + <% end %> +</ul> + +<%= link_to "New Post", new_admin_post_path %> \ No newline at end of file diff --git a/app/views/twibblr/admin/posts/new.html.erb b/app/views/twibblr/admin/posts/new.html.erb new file mode 100644 index 0000000..fab87ff --- /dev/null +++ b/app/views/twibblr/admin/posts/new.html.erb @@ -0,0 +1,15 @@ +<% form_for :post, @post, :url => admin_posts_path do |f| %> + <%= error_messages_for :post %> + <p> + <%= f.label :title %> + <br /> + <%= f.text_field :title %> + </p> + <p> + <%= f.label :body %> + <br /> + <%= f.text_area :body %> + </p> + + <%= f.submit "Create" %> +<% end %> \ No newline at end of file diff --git a/app/views/twibblr/posts/show.html.erb b/app/views/twibblr/posts/show.html.erb index 3f39a89..42841f9 100644 --- a/app/views/twibblr/posts/show.html.erb +++ b/app/views/twibblr/posts/show.html.erb @@ -1 +1 @@ -<%= render :partial => @post %> \ No newline at end of file +<%= render :partial => 'post', :collection => @post %> \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 832a155..827a18b 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,33 +1,33 @@ YEAR_REGEX = /\d{4}/ MONTH_REGEX = /(?:0?[1-9]|1[012])/ DAY_REGEX = /(?:0?[1-9]|[12][0-9]|3[01])/ PARAM_REGEX = /\d+(?:-[a-z0-9_-]+?)?/ ActionController::Routing::Routes.draw do |map| map.with_options :conditions => {:method => :get} do |get| get.with_options :controller => "twibblr/posts" do |posts| posts.with_options :action => "index" do |list_posts| list_posts.root - list_posts.posts "/posts" - list_posts.formatted_posts "/posts.:format" - list_posts.map "/:year", :requirements => {:year => YEAR_REGEX} - list_posts.map "/:year/:month", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX} - list_posts.map "/:year/:month/:day", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX, :day => DAY_REGEX} + list_posts.posts "/posts.:format" + list_posts.map "/:year.:format", :requirements => {:year => YEAR_REGEX} + list_posts.map "/:year/:month.:format", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX} + list_posts.map "/:year/:month/:day.:format", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX, :day => DAY_REGEX} end posts.map "/tags/:tag", :action => "by_tag" options = {:action => "show", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX, :day => DAY_REGEX, :id => PARAM_REGEX}} posts.post "/:year/:month/:day/:id", options + posts.post "/posts/:id", :action => "show" posts.formatted_post "/:year/:month/:day/:id.:format", options end end map.namespace :admin, :namespace => "twibblr/" do |admin| admin.root :controller => 'admin', :action => 'index' admin.resources :posts admin.resources :tags end end \ No newline at end of file
bjeanes/twibblr
dabe7ee7a8b3c2611426214567cb16a6325184c0
Add admin link to sidebar
diff --git a/app/views/layouts/_sidebar.html.erb b/app/views/layouts/_sidebar.html.erb index ade02a0..94136f2 100644 --- a/app/views/layouts/_sidebar.html.erb +++ b/app/views/layouts/_sidebar.html.erb @@ -1,20 +1,21 @@ <div id="sidebar"> - <ul> - <li> - <h2>Updates:</h2> - <ul> - <% render_posts(:limit => 5) do |post| %> - <li><%= link_to post.title, post.link %></li> - <% end %> - </ul> - </li> - <li> - <h2>Tags</h2> - <ul> - <% render_tags do |tag| %> - <li><%= link_to "#{tag} (#{tag.posts_count})", "/tags/#{tag.permalink}" %></li> - <% end %> - </ul> - </li> - </ul> - </div> \ No newline at end of file + <ul> + <li> + <h2>Updates:</h2> + <ul> + <% render_posts(:limit => 5) do |post| %> + <li><%= link_to post.title, post.link %></li> + <% end %> + </ul> + </li> + <li> + <h2>Tags</h2> + <ul> + <% render_tags do |tag| %> + <li><%= link_to "#{tag} (#{tag.posts_count})", "/tags/#{tag.permalink}" %></li> + <% end %> + </ul> + </li> + <li><%= link_to "Admin", admin_root_path %></li> + </ul> +</div> \ No newline at end of file
bjeanes/twibblr
8a524e1b833403b513e38b7c1279cd165d2d19e5
Admin panel
diff --git a/app/views/twibblr/admin/admin/index.html.erb b/app/views/twibblr/admin/admin/index.html.erb index 214a88e..faf1afe 100644 --- a/app/views/twibblr/admin/admin/index.html.erb +++ b/app/views/twibblr/admin/admin/index.html.erb @@ -1 +1,2 @@ -admin panel \ No newline at end of file +<%= link_to "Posts", admin_posts_path %><br /> +<%= link_to "Tags", admin_tags_path %> \ No newline at end of file diff --git a/app/views/twibblr/admin/posts/index.html.erb b/app/views/twibblr/admin/posts/index.html.erb new file mode 100644 index 0000000..09af61c --- /dev/null +++ b/app/views/twibblr/admin/posts/index.html.erb @@ -0,0 +1 @@ +Show posts here \ No newline at end of file
bjeanes/twibblr
9cc8c7e62d29b9b118ba9ecd44d35ab04b1c8e1f
Just use BasicAuth for the admin panel for now until twitter OAuth integration can be set up
diff --git a/app/controllers/twibblr/admin/admin_controller.rb b/app/controllers/twibblr/admin/admin_controller.rb index 7e5ea0d..34248ff 100644 --- a/app/controllers/twibblr/admin/admin_controller.rb +++ b/app/controllers/twibblr/admin/admin_controller.rb @@ -1,21 +1,20 @@ module Twibblr module Admin class AdminController < ::Twibblr::BaseController - # before_filter :ensure_login + before_filter :log_in_required layout 'twibblr_admin' def index end protected - def ensure_login - unless logged_in? && authorised? - flash[:error] = "You must have permission to access this resource." - redirect_to root_path + def log_in_required + authenticate_or_request_with_http_basic do |login, password| + login == CONFIG['username'].to_s && password == CONFIG['password'].to_s end end end end end \ No newline at end of file diff --git a/app/controllers/twibblr/base_controller.rb b/app/controllers/twibblr/base_controller.rb index 6a6b1b0..e175d01 100644 --- a/app/controllers/twibblr/base_controller.rb +++ b/app/controllers/twibblr/base_controller.rb @@ -1,20 +1,18 @@ # Define a master controller for plugin to have defaults set everywhere module Twibblr class BaseController < ::ApplicationController helper 'twibblr/main' filter_parameter_logging :password layout :choose_layout protected - - include Authentication def development? RAILS_ENV == "development" end def choose_layout CONFIG['layout'] end end end \ No newline at end of file diff --git a/config/twibblr.yml.erb b/config/twibblr.yml.erb index f0d224e..fc3ff7b 100644 --- a/config/twibblr.yml.erb +++ b/config/twibblr.yml.erb @@ -1,2 +1,4 @@ site_name: <%= File.basename(RAILS_ROOT) %> +username: <%= `whoami`.chomp %> +password: layout: twibblr \ No newline at end of file diff --git a/init.rb b/init.rb index e627d60..94235de 100644 --- a/init.rb +++ b/init.rb @@ -1,16 +1,15 @@ require 'yaml' -require 'twibblr/authentication' # This ensures that helpers reload in development as well ActiveSupport::Dependencies.load_once_paths.clear if RAILS_ENV == "development" module ::Twibblr CONFIG = YAML.load_file(File.join(RAILS_ROOT, 'config', 'twibblr.yml')) end Twibblr::ROOT = self.directory # Load plug-in initializers Dir.chdir(File.join(Twibblr::ROOT, "config", "initializers")) do Dir["*.rb"].each { |file| require file } end \ No newline at end of file diff --git a/lib/twibblr/authentication.rb b/lib/twibblr/authentication.rb deleted file mode 100644 index 8da9ba5..0000000 --- a/lib/twibblr/authentication.rb +++ /dev/null @@ -1,21 +0,0 @@ -module Twibblr - module Authentication - protected - - def logged_in? - !!current_user - end - - def current_user - nil - end - - def authorised? - false - end - - def authorized? - authorised? - end - end -end \ No newline at end of file
bjeanes/twibblr
d383ed0f2fa7ecb4721b9b0379b2935f2dc0c2c4
added to do list
diff --git a/README b/README index 494a753..38fd5e9 100644 --- a/README +++ b/README @@ -1,13 +1,22 @@ Twibblr ======= A Rails Engine for adding blogging (and much more to come later, such as github commit history, tweets, flicer integration, etc) to an existing site. The aim is to have completely non-conflicting models, controllers, et cetera and to allow mounting the system anywhere (/posts, /subdir/posts, etc) Install ======= script/plugin install git://github.com/bjeanes/twibblr.git # run rake twibblr:install if you don't see instructions rake db:migrate + +To do +===== + +* use twitter to authenticate for admin +* show tweets in feeds \ +* github commits \____ use STI +* flickr / + Copyright (c) 2009 Bodaniel Jeanes, released under the MIT license \ No newline at end of file
bjeanes/twibblr
77158bd0808d922283126286ab11291250c95322
More admin panel frameworks + routes
diff --git a/app/controllers/twibblr/admin/admin_controller.rb b/app/controllers/twibblr/admin/admin_controller.rb index e0ecfc7..7e5ea0d 100644 --- a/app/controllers/twibblr/admin/admin_controller.rb +++ b/app/controllers/twibblr/admin/admin_controller.rb @@ -1,16 +1,21 @@ module Twibblr module Admin class AdminController < ::Twibblr::BaseController - before_filter :ensure_login + # before_filter :ensure_login + layout 'twibblr_admin' + + def index + + end protected def ensure_login unless logged_in? && authorised? flash[:error] = "You must have permission to access this resource." redirect_to root_path end end end end end \ No newline at end of file diff --git a/app/controllers/twibblr/admin/posts_controller.rb b/app/controllers/twibblr/admin/posts_controller.rb index eedcb99..debc4f8 100644 --- a/app/controllers/twibblr/admin/posts_controller.rb +++ b/app/controllers/twibblr/admin/posts_controller.rb @@ -1,10 +1,6 @@ module Twibblr module Admin class PostsController < AdminController - - def index - render_text "Admin Posts will go here" - end end end end \ No newline at end of file diff --git a/app/views/layouts/twibblr_admin.html.erb b/app/views/layouts/twibblr_admin.html.erb new file mode 100644 index 0000000..43c158b --- /dev/null +++ b/app/views/layouts/twibblr_admin.html.erb @@ -0,0 +1,16 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> + + <title><%= site_name %> Admin</title> + +</head> + +<body> +<%= yield %> + +</body> +</html> diff --git a/app/views/twibblr/admin/admin/index.html.erb b/app/views/twibblr/admin/admin/index.html.erb new file mode 100644 index 0000000..214a88e --- /dev/null +++ b/app/views/twibblr/admin/admin/index.html.erb @@ -0,0 +1 @@ +admin panel \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index d259bd8..832a155 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,30 +1,33 @@ YEAR_REGEX = /\d{4}/ MONTH_REGEX = /(?:0?[1-9]|1[012])/ DAY_REGEX = /(?:0?[1-9]|[12][0-9]|3[01])/ PARAM_REGEX = /\d+(?:-[a-z0-9_-]+?)?/ ActionController::Routing::Routes.draw do |map| map.with_options :conditions => {:method => :get} do |get| get.with_options :controller => "twibblr/posts" do |posts| posts.with_options :action => "index" do |list_posts| list_posts.root list_posts.posts "/posts" list_posts.formatted_posts "/posts.:format" list_posts.map "/:year", :requirements => {:year => YEAR_REGEX} list_posts.map "/:year/:month", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX} list_posts.map "/:year/:month/:day", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX, :day => DAY_REGEX} end posts.map "/tags/:tag", :action => "by_tag" - options = {:action => "show", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX, :day => DAY_REGEX, :id => PARAM_REGEX}} + options = {:action => "show", :requirements => + {:year => YEAR_REGEX, :month => MONTH_REGEX, :day => DAY_REGEX, :id => PARAM_REGEX}} posts.post "/:year/:month/:day/:id", options posts.formatted_post "/:year/:month/:day/:id.:format", options end end map.namespace :admin, :namespace => "twibblr/" do |admin| + admin.root :controller => 'admin', :action => 'index' admin.resources :posts + admin.resources :tags end end \ No newline at end of file
bjeanes/twibblr
b44a16f5a8b8625c97f2ef32618510e36bd2c0c5
Starting admin panel
diff --git a/app/controllers/twibblr/admin/admin_controller.rb b/app/controllers/twibblr/admin/admin_controller.rb new file mode 100644 index 0000000..e0ecfc7 --- /dev/null +++ b/app/controllers/twibblr/admin/admin_controller.rb @@ -0,0 +1,16 @@ +module Twibblr + module Admin + class AdminController < ::Twibblr::BaseController + before_filter :ensure_login + + protected + + def ensure_login + unless logged_in? && authorised? + flash[:error] = "You must have permission to access this resource." + redirect_to root_path + end + end + end + end +end \ No newline at end of file diff --git a/app/controllers/twibblr/admin/posts_controller.rb b/app/controllers/twibblr/admin/posts_controller.rb new file mode 100644 index 0000000..eedcb99 --- /dev/null +++ b/app/controllers/twibblr/admin/posts_controller.rb @@ -0,0 +1,10 @@ +module Twibblr + module Admin + class PostsController < AdminController + + def index + render_text "Admin Posts will go here" + end + end + end +end \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index ed7da71..d259bd8 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,26 +1,30 @@ YEAR_REGEX = /\d{4}/ MONTH_REGEX = /(?:0?[1-9]|1[012])/ DAY_REGEX = /(?:0?[1-9]|[12][0-9]|3[01])/ PARAM_REGEX = /\d+(?:-[a-z0-9_-]+?)?/ ActionController::Routing::Routes.draw do |map| map.with_options :conditions => {:method => :get} do |get| get.with_options :controller => "twibblr/posts" do |posts| posts.with_options :action => "index" do |list_posts| list_posts.root list_posts.posts "/posts" list_posts.formatted_posts "/posts.:format" list_posts.map "/:year", :requirements => {:year => YEAR_REGEX} list_posts.map "/:year/:month", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX} list_posts.map "/:year/:month/:day", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX, :day => DAY_REGEX} end posts.map "/tags/:tag", :action => "by_tag" options = {:action => "show", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX, :day => DAY_REGEX, :id => PARAM_REGEX}} posts.post "/:year/:month/:day/:id", options posts.formatted_post "/:year/:month/:day/:id.:format", options end end + + map.namespace :admin, :namespace => "twibblr/" do |admin| + admin.resources :posts + end end \ No newline at end of file
bjeanes/twibblr
18036fdd65887fb4209d356179601fd9a7470381
Load the layout from a config file
diff --git a/app/controllers/twibblr/base_controller.rb b/app/controllers/twibblr/base_controller.rb index 99c8c37..6a6b1b0 100644 --- a/app/controllers/twibblr/base_controller.rb +++ b/app/controllers/twibblr/base_controller.rb @@ -1,21 +1,20 @@ # Define a master controller for plugin to have defaults set everywhere module Twibblr class BaseController < ::ApplicationController helper 'twibblr/main' filter_parameter_logging :password layout :choose_layout protected include Authentication def development? RAILS_ENV == "development" end def choose_layout - # This ivar could be set by some form of site config later - @layout ||= "twibblr" + CONFIG['layout'] end end end \ No newline at end of file diff --git a/config/twibblr.yml.erb b/config/twibblr.yml.erb index 05ebe02..f0d224e 100644 --- a/config/twibblr.yml.erb +++ b/config/twibblr.yml.erb @@ -1 +1,2 @@ -site_name: <%= File.basename(RAILS_ROOT) %> \ No newline at end of file +site_name: <%= File.basename(RAILS_ROOT) %> +layout: twibblr \ No newline at end of file
bjeanes/twibblr
ba3733b61bc5830de3d6fc1cb0bfea11e8f5e640
Changed models to use tables with twibblr as a prefix
diff --git a/app/models/twibblr/comment.rb b/app/models/twibblr/comment.rb index b400b89..59182d2 100644 --- a/app/models/twibblr/comment.rb +++ b/app/models/twibblr/comment.rb @@ -1,4 +1,5 @@ class Twibblr::Comment < ActiveRecord::Base + set_table_name :twibblr_comments belongs_to :post validates_presence_of :name, :email end diff --git a/app/models/twibblr/post.rb b/app/models/twibblr/post.rb index f396a88..cc346d2 100644 --- a/app/models/twibblr/post.rb +++ b/app/models/twibblr/post.rb @@ -1,36 +1,38 @@ class Twibblr::Post < ActiveRecord::Base + set_table_name :twibblr_posts + default_scope :order => "created_at DESC" has_many :comments, :order => "created_at ASC" has_many :posts_tags has_many :tags, :through => :posts_tags, :order => "name ASC" named_scope :archive, :group => "month(created_at)" validates_presence_of :body, :title %w{year month day}.each do |time| delegate time, :to => :created_at named_scope :"in_#{time}", lambda { |num| {:conditions => ["#{time.upcase}(created_at) = ?", num] } } end def date created_at.to_date.to_s(:long_ordinal) end def to_s title end def link @link ||= "/#{created_at.year}/#{created_at.month}/#{created_at.day}/#{to_param}" end def to_param if title.blank? id else "#{id}-#{title.parameterize}" end end end \ No newline at end of file diff --git a/app/models/twibblr/posts_tag.rb b/app/models/twibblr/posts_tag.rb index c83d8ee..922ff09 100644 --- a/app/models/twibblr/posts_tag.rb +++ b/app/models/twibblr/posts_tag.rb @@ -1,4 +1,5 @@ class Twibblr::PostsTag < ActiveRecord::Base + set_table_name :twibblr_posts_tags belongs_to :post belongs_to :tag, :counter_cache => "posts_count" end \ No newline at end of file diff --git a/app/models/twibblr/tag.rb b/app/models/twibblr/tag.rb index b8f07bc..80b0311 100644 --- a/app/models/twibblr/tag.rb +++ b/app/models/twibblr/tag.rb @@ -1,33 +1,35 @@ class Twibblr::Tag < ActiveRecord::Base + set_table_name :twibblr_tags + default_scope :order => "posts_count", :conditions => ["posts_count > ?", 0] has_many :posts_tags has_many :posts, :through => :posts_tags, :order => "created_at ASC" before_create :set_permalink before_save :lowercase_name def to_s name end def to_param permalink end def self.[](identifier) identifier.is_a?(Fixnum) ? find(identifier) : find(:first, :conditions => ["name = :name OR permalink = :name", {:name => identifier.to_s}]) rescue nil end private def set_permalink self.permalink = name.parameterize if permalink.blank? end def lowercase_name self.name.downcase! end end \ No newline at end of file diff --git a/db/migrate/20090208091453_create_posts.rb b/db/migrate/20090208091453_create_posts.rb index e4c8227..7eba07b 100644 --- a/db/migrate/20090208091453_create_posts.rb +++ b/db/migrate/20090208091453_create_posts.rb @@ -1,13 +1,13 @@ class CreatePosts < ActiveRecord::Migration def self.up - create_table :posts, :force => true do |t| + create_table :twibblr_posts, :force => true do |t| t.string :title t.text :body t.timestamps end end def self.down - drop_table :posts + drop_table :twibblr_posts end end diff --git a/db/migrate/20090210222840_create_comments.rb b/db/migrate/20090210222840_create_comments.rb index 80f71ca..a6c11e9 100644 --- a/db/migrate/20090210222840_create_comments.rb +++ b/db/migrate/20090210222840_create_comments.rb @@ -1,16 +1,16 @@ class CreateComments < ActiveRecord::Migration def self.up - create_table :comments do |t| + create_table :twibblr_comments do |t| t.references :post t.text :body t.string :name t.string :email t.string :website t.timestamps end end def self.down - drop_table :comments + drop_table :twibblr_comments end end diff --git a/db/migrate/20090210223500_create_tags.rb b/db/migrate/20090210223500_create_tags.rb index 7186447..86e1a05 100644 --- a/db/migrate/20090210223500_create_tags.rb +++ b/db/migrate/20090210223500_create_tags.rb @@ -1,22 +1,22 @@ class CreateTags < ActiveRecord::Migration def self.up - create_table :tags do |t| + create_table :twibblr_tags do |t| t.string :name t.string :permalink end - create_table :posts_tags, :id => false do |t| + create_table :twibblr_posts_tags, :id => false do |t| t.references :tag t.references :post end - add_index :tags, :name, :unique => true - add_index :tags, :permalink, :unique => true - add_index :posts_tags, [:post_id, :tag_id], :unique => true + add_index :twibblr_tags, :name, :unique => true + add_index :twibblr_tags, :permalink, :unique => true + add_index :twibblr_posts_tags, [:post_id, :tag_id], :unique => true end def self.down - drop_table :tags - drop_table :posts_tags + drop_table :twibblr_tags + drop_table :twibblr_posts_tags end end diff --git a/db/migrate/20090216162012_add_posts_count_to_tags.rb b/db/migrate/20090216162012_add_posts_count_to_tags.rb index 6a078dd..b3866da 100644 --- a/db/migrate/20090216162012_add_posts_count_to_tags.rb +++ b/db/migrate/20090216162012_add_posts_count_to_tags.rb @@ -1,9 +1,9 @@ class AddPostsCountToTags < ActiveRecord::Migration def self.up - add_column :tags, :posts_count, :integer, :default => 0 + add_column :twibblr_tags, :posts_count, :integer, :default => 0 end def self.down - remove_column :tags, :posts_count + remove_column :twibblr_tags, :posts_count end end
bjeanes/twibblr
16d51da48b48ef3956a390b15e07456476313534
Fixed typo and put sidebar in a partial
diff --git a/app/controllers/twibblr/base_controller.rb b/app/controllers/twibblr/base_controller.rb index 2141789..99c8c37 100644 --- a/app/controllers/twibblr/base_controller.rb +++ b/app/controllers/twibblr/base_controller.rb @@ -1,21 +1,21 @@ # Define a master controller for plugin to have defaults set everywhere module Twibblr class BaseController < ::ApplicationController helper 'twibblr/main' filter_parameter_logging :password layout :choose_layout protected - include Authenticationon + include Authentication def development? RAILS_ENV == "development" end def choose_layout # This ivar could be set by some form of site config later @layout ||= "twibblr" end end end \ No newline at end of file diff --git a/app/views/layouts/_sidebar.html.erb b/app/views/layouts/_sidebar.html.erb new file mode 100644 index 0000000..ade02a0 --- /dev/null +++ b/app/views/layouts/_sidebar.html.erb @@ -0,0 +1,20 @@ +<div id="sidebar"> + <ul> + <li> + <h2>Updates:</h2> + <ul> + <% render_posts(:limit => 5) do |post| %> + <li><%= link_to post.title, post.link %></li> + <% end %> + </ul> + </li> + <li> + <h2>Tags</h2> + <ul> + <% render_tags do |tag| %> + <li><%= link_to "#{tag} (#{tag.posts_count})", "/tags/#{tag.permalink}" %></li> + <% end %> + </ul> + </li> + </ul> + </div> \ No newline at end of file diff --git a/app/views/layouts/twibblr.html.erb b/app/views/layouts/twibblr.html.erb index d4293b4..fd09d42 100644 --- a/app/views/layouts/twibblr.html.erb +++ b/app/views/layouts/twibblr.html.erb @@ -1,64 +1,46 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title><%= site_name %> - powered by Twibblr</title> <meta name="keywords" content="" /> <meta name="description" content="" /> <link href="/twibblr/stylesheets/master.css" rel="stylesheet" type="text/css" media="screen" /> <%= yield :head %> </head> <body> <!-- start header --> <div id="header"> <div id="logo"> <h1><%= link_to site_name, "/" %></h1> <p>Powered by <a href="http://github.com/bjeanes/twibblr">Twibblr</a></p> </div> <div id="search"> <form method="get" action=""> <fieldset> <input id="s" type="text" name="s" value="" /> <input id="x" type="submit" value="Search" /> </fieldset> </form> </div> </div> <!-- end header --> <!-- start page --> <div id="page"> <!-- start content --> <div id="content"> <%= yield %> </div> <!-- end content --> <!-- start sidebar --> - <div id="sidebar"> - <ul> - <li> - <h2>Updates:</h2> - <ul> - <% render_posts(:limit => 5) do |post| %> - <li><%= link_to post.title, post.link %></li> - <% end %> - </ul> - </li> - <li> - <h2>Tags</h2> - <ul> - <% render_tags do |tag| %> - <li><%= link_to "#{tag} (#{tag.posts_count})", "/tags/#{tag.permalink}" %></li> - <% end %> - </ul> - </li> - </ul> - </div> + <%= render :partial => 'layouts/sidebar' %> + <!-- end sidebar --> </div> <!-- end page --> <div id="footer"> <p>&copy;2007 All Rights Reserved. &nbsp;&bull;&nbsp; Design by <a href="http://templatefusion.org">TemplateFusion</a> &nbsp;&bull;&nbsp; Icons by <a href="http://www.famfamfam.com/">FAMFAMFAM</a>.</p> </div> </body> </html> \ No newline at end of file
bjeanes/twibblr
45d08e299d555676a7b5d312842164f825fde160
Include some authentication stubs that the plugin expects to be implemented
diff --git a/app/controllers/twibblr/base_controller.rb b/app/controllers/twibblr/base_controller.rb index 0ea0c13..2141789 100644 --- a/app/controllers/twibblr/base_controller.rb +++ b/app/controllers/twibblr/base_controller.rb @@ -1,19 +1,21 @@ # Define a master controller for plugin to have defaults set everywhere module Twibblr class BaseController < ::ApplicationController helper 'twibblr/main' filter_parameter_logging :password layout :choose_layout protected + + include Authenticationon def development? RAILS_ENV == "development" end def choose_layout # This ivar could be set by some form of site config later @layout ||= "twibblr" end end end \ No newline at end of file diff --git a/lib/twibblr/authentication.rb b/lib/twibblr/authentication.rb index 8747f07..8da9ba5 100644 --- a/lib/twibblr/authentication.rb +++ b/lib/twibblr/authentication.rb @@ -1,5 +1,21 @@ module Twibblr module Authentication + protected + def logged_in? + !!current_user + end + + def current_user + nil + end + + def authorised? + false + end + + def authorized? + authorised? + end end end \ No newline at end of file
bjeanes/twibblr
e2dad7dfa9720f55e0cc828288fd893c5f2b502a
only show tags that have posts by default
diff --git a/app/models/twibblr/tag.rb b/app/models/twibblr/tag.rb index 2902cc4..b8f07bc 100644 --- a/app/models/twibblr/tag.rb +++ b/app/models/twibblr/tag.rb @@ -1,33 +1,33 @@ class Twibblr::Tag < ActiveRecord::Base - default_scope :order => "posts_count" + default_scope :order => "posts_count", :conditions => ["posts_count > ?", 0] has_many :posts_tags has_many :posts, :through => :posts_tags, :order => "created_at ASC" before_create :set_permalink before_save :lowercase_name def to_s name end def to_param permalink end def self.[](identifier) identifier.is_a?(Fixnum) ? find(identifier) : find(:first, :conditions => ["name = :name OR permalink = :name", {:name => identifier.to_s}]) rescue nil end private def set_permalink self.permalink = name.parameterize if permalink.blank? end def lowercase_name self.name.downcase! end end \ No newline at end of file
bjeanes/twibblr
cda74fa50b8bbfd7fa11c289bd9426d13d238fd9
require authentication library (which will just be stubs for overriding)
diff --git a/init.rb b/init.rb index 94235de..e627d60 100644 --- a/init.rb +++ b/init.rb @@ -1,15 +1,16 @@ require 'yaml' +require 'twibblr/authentication' # This ensures that helpers reload in development as well ActiveSupport::Dependencies.load_once_paths.clear if RAILS_ENV == "development" module ::Twibblr CONFIG = YAML.load_file(File.join(RAILS_ROOT, 'config', 'twibblr.yml')) end Twibblr::ROOT = self.directory # Load plug-in initializers Dir.chdir(File.join(Twibblr::ROOT, "config", "initializers")) do Dir["*.rb"].each { |file| require file } end \ No newline at end of file diff --git a/lib/twibblr/authentication.rb b/lib/twibblr/authentication.rb index c962858..8747f07 100644 --- a/lib/twibblr/authentication.rb +++ b/lib/twibblr/authentication.rb @@ -1,5 +1,5 @@ module Twibblr module Authentication - + end end \ No newline at end of file
bjeanes/twibblr
46b65ee12867444fc3c4ae08648cd6735779e5ab
Some README work
diff --git a/README b/README index 13d06f7..494a753 100644 --- a/README +++ b/README @@ -1,13 +1,13 @@ Twibblr ======= -Introduction goes here. +A Rails Engine for adding blogging (and much more to come later, such as github commit history, tweets, flicer integration, etc) to an existing site. The aim is to have completely non-conflicting models, controllers, et cetera and to allow mounting the system anywhere (/posts, /subdir/posts, etc) - -Example +Install ======= -Example goes here. - + script/plugin install git://github.com/bjeanes/twibblr.git + # run rake twibblr:install if you don't see instructions + rake db:migrate -Copyright (c) 2009 Bodaniel Jeanes, released under the MIT license +Copyright (c) 2009 Bodaniel Jeanes, released under the MIT license \ No newline at end of file
bjeanes/twibblr
0a715467120f197690a3838a0b384e19cb9a0749
Load in the site name into templates using the config yaml file
diff --git a/app/helpers/twibblr/main_helper.rb b/app/helpers/twibblr/main_helper.rb index 226ccb9..ed97df6 100644 --- a/app/helpers/twibblr/main_helper.rb +++ b/app/helpers/twibblr/main_helper.rb @@ -1,38 +1,46 @@ module Twibblr::MainHelper def render_posts(*args, &block) # if they are fetching posts in the controller # then awesome(!) otherwise get it for them posts = @posts || Post.all(*args) if block_given? posts.each do |post| render_post(post, &block) end else render :partial => posts end end def render_tags(*args) raise "No Block Given" unless block_given? options = {:order => "name"}.merge(args.extract_options!) args << options (@tags || Tag.all(*args)).each {|tag| yield(tag)} end + + def site_name + config['site_name'].titleize || 'My website' + end + + def config + Twibblr::CONFIG + end private def render_post(post, &block) raise "No block given" unless block_given? case block.arity when 1 then yield(post) when 2 then yield(post.title, post.body) when 3 then yield(post.title, post.body, post.created_at) when 4 then yield(post.title, post.body, post.created_at, post.tags) when 5 then yield(post.title, post.body, post.created_at, post.tags, post.comments) else raise "Parameter Error" end end end \ No newline at end of file diff --git a/app/views/layouts/twibblr.html.erb b/app/views/layouts/twibblr.html.erb index 8d72def..d4293b4 100644 --- a/app/views/layouts/twibblr.html.erb +++ b/app/views/layouts/twibblr.html.erb @@ -1,64 +1,64 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> - <title>My website - powered by Twibblr</title> + <title><%= site_name %> - powered by Twibblr</title> <meta name="keywords" content="" /> <meta name="description" content="" /> <link href="/twibblr/stylesheets/master.css" rel="stylesheet" type="text/css" media="screen" /> <%= yield :head %> </head> <body> <!-- start header --> <div id="header"> <div id="logo"> - <h1><%= link_to "My Website", "/" %></h1> + <h1><%= link_to site_name, "/" %></h1> <p>Powered by <a href="http://github.com/bjeanes/twibblr">Twibblr</a></p> </div> <div id="search"> <form method="get" action=""> <fieldset> <input id="s" type="text" name="s" value="" /> <input id="x" type="submit" value="Search" /> </fieldset> </form> </div> </div> <!-- end header --> <!-- start page --> <div id="page"> <!-- start content --> <div id="content"> <%= yield %> </div> <!-- end content --> <!-- start sidebar --> <div id="sidebar"> <ul> <li> <h2>Updates:</h2> <ul> <% render_posts(:limit => 5) do |post| %> <li><%= link_to post.title, post.link %></li> <% end %> </ul> </li> <li> <h2>Tags</h2> <ul> <% render_tags do |tag| %> <li><%= link_to "#{tag} (#{tag.posts_count})", "/tags/#{tag.permalink}" %></li> <% end %> </ul> </li> </ul> </div> <!-- end sidebar --> </div> <!-- end page --> <div id="footer"> <p>&copy;2007 All Rights Reserved. &nbsp;&bull;&nbsp; Design by <a href="http://templatefusion.org">TemplateFusion</a> &nbsp;&bull;&nbsp; Icons by <a href="http://www.famfamfam.com/">FAMFAMFAM</a>.</p> </div> </body> </html> \ No newline at end of file diff --git a/init.rb b/init.rb index 9635da9..94235de 100644 --- a/init.rb +++ b/init.rb @@ -1,12 +1,15 @@ -# We want to reload all the controllers, helpers, and -# models if we are in development mode: +require 'yaml' + +# This ensures that helpers reload in development as well ActiveSupport::Dependencies.load_once_paths.clear if RAILS_ENV == "development" -module Twibblr - ROOT = File.expand_path(File.dirname(__FILE__)) +module ::Twibblr + CONFIG = YAML.load_file(File.join(RAILS_ROOT, 'config', 'twibblr.yml')) end +Twibblr::ROOT = self.directory + # Load plug-in initializers Dir.chdir(File.join(Twibblr::ROOT, "config", "initializers")) do Dir["*.rb"].each { |file| require file } end \ No newline at end of file
bjeanes/twibblr
27e3868cdb8b1ce64a1465367c0988d601618d35
Made installer a bit more robust and puts a config yml file into the config directly
diff --git a/config/twibblr.yml.erb b/config/twibblr.yml.erb new file mode 100644 index 0000000..05ebe02 --- /dev/null +++ b/config/twibblr.yml.erb @@ -0,0 +1 @@ +site_name: <%= File.basename(RAILS_ROOT) %> \ No newline at end of file diff --git a/install.rb b/install.rb index f7732d3..10eb878 100644 --- a/install.rb +++ b/install.rb @@ -1 +1,14 @@ -# Install hook code here +require 'erb' + +plugin_path = File.expand_path(File.dirname(__FILE__)) + +puts "Installing migrations" +system "rsync -ru #{plugin_path}/db/migrate db" + +puts "Installing static files" +system "rsync -ru --delete #{plugin_path}/public/ public/twibblr" + +puts "Installing twibblr config file" +raw_config = File.read("#{plugin_path}/config/twibblr.yml.erb") +erb_config = ERB.new(raw_config).result +File.open(File.join(RAILS_ROOT, 'config', 'twibblr.yml'), 'w') { |f| f.write(erb_config) } diff --git a/lib/twibblr/authentication.rb b/lib/twibblr/authentication.rb new file mode 100644 index 0000000..c962858 --- /dev/null +++ b/lib/twibblr/authentication.rb @@ -0,0 +1,5 @@ +module Twibblr + module Authentication + + end +end \ No newline at end of file diff --git a/tasks/install.rake b/tasks/install.rake index 9f17460..d3d3e79 100644 --- a/tasks/install.rake +++ b/tasks/install.rake @@ -1,7 +1,9 @@ namespace :twibblr do - task :install do - # From railscasts #149 - system "rsync -ruv vendor/plugins/twibblr/db/migrate db" - system "rsync -ruv --delete vendor/plugins/twibblr/public/ public/twibblr" + task :install => [:environment] do + require File.join(File.dirname(__FILE__), '..', 'install') + end + + task :uninstall do + require File.join(File.dirname(__FILE__), '..', 'uninstall') end end diff --git a/uninstall.rb b/uninstall.rb index 9738333..457d0f5 100644 --- a/uninstall.rb +++ b/uninstall.rb @@ -1 +1,3 @@ # Uninstall hook code here + +system "rm -rf public/twibblr" \ No newline at end of file
bjeanes/twibblr
e08e85ba71de81971df135e26b74ffa236efa7db
Namespaced module as well
diff --git a/app/controllers/twibblr/base_controller.rb b/app/controllers/twibblr/base_controller.rb index 029b7e8..0ea0c13 100644 --- a/app/controllers/twibblr/base_controller.rb +++ b/app/controllers/twibblr/base_controller.rb @@ -1,19 +1,19 @@ # Define a master controller for plugin to have defaults set everywhere module Twibblr class BaseController < ::ApplicationController - helper :twibblr + helper 'twibblr/main' filter_parameter_logging :password layout :choose_layout protected def development? RAILS_ENV == "development" end def choose_layout # This ivar could be set by some form of site config later @layout ||= "twibblr" end end end \ No newline at end of file diff --git a/app/helpers/twibblr_helper.rb b/app/helpers/twibblr/main_helper.rb similarity index 87% rename from app/helpers/twibblr_helper.rb rename to app/helpers/twibblr/main_helper.rb index 6414106..226ccb9 100644 --- a/app/helpers/twibblr_helper.rb +++ b/app/helpers/twibblr/main_helper.rb @@ -1,38 +1,38 @@ -module TwibblrHelper +module Twibblr::MainHelper def render_posts(*args, &block) # if they are fetching posts in the controller # then awesome(!) otherwise get it for them - posts = @posts || Twibblr::Post.all(*args) + posts = @posts || Post.all(*args) if block_given? posts.each do |post| render_post(post, &block) end else render :partial => posts end end def render_tags(*args) raise "No Block Given" unless block_given? options = {:order => "name"}.merge(args.extract_options!) args << options - (@tags || Twibblr::Tag.all(*args)).each {|tag| yield(tag)} + (@tags || Tag.all(*args)).each {|tag| yield(tag)} end private def render_post(post, &block) raise "No block given" unless block_given? case block.arity when 1 then yield(post) when 2 then yield(post.title, post.body) when 3 then yield(post.title, post.body, post.created_at) when 4 then yield(post.title, post.body, post.created_at, post.tags) when 5 then yield(post.title, post.body, post.created_at, post.tags, post.comments) else raise "Parameter Error" end end end \ No newline at end of file
bjeanes/twibblr
e2030df93fc11e9fbd96e589461759760bc3a44b
Namespaced everything so as not to conflict
diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rb deleted file mode 100644 index 3dd0981..0000000 --- a/app/controllers/posts_controller.rb +++ /dev/null @@ -1,41 +0,0 @@ -class PostsController < TwibblrController - before_filter :filter_by_time, :only => [:index, :show] - - def index - @posts = @posts.all - respond_to do |format| - format.html - format.rss { render :layout => false } - end - end - - def by_tag - @posts = Tag.find_by_permalink(params[:tag]).posts - render :index - rescue - flash[:error] = "Tag '#{params[:tag]}' does not exist." - redirect_to :action => :index - end - - def show - @post = @posts.find(params[:id].to_i, :include => :comments) - - @comments = @post.comments - @comment = Comment.new - - respond_to do |format| - format.html # show.html.erb - format.rss { render :layout => false } - end - end - - protected - - # TODO: this needs to be cleaner!!! - def filter_by_time - @posts = Post - @posts = @posts.in_year(params[:year]) if params[:year] - @posts = @posts.in_month(params[:month]) if params[:month] - @posts = @posts.in_day(params[:day]) if params[:day] - end -end \ No newline at end of file diff --git a/app/controllers/twibblr/base_controller.rb b/app/controllers/twibblr/base_controller.rb new file mode 100644 index 0000000..029b7e8 --- /dev/null +++ b/app/controllers/twibblr/base_controller.rb @@ -0,0 +1,19 @@ +# Define a master controller for plugin to have defaults set everywhere +module Twibblr + class BaseController < ::ApplicationController + helper :twibblr + filter_parameter_logging :password + layout :choose_layout + + protected + + def development? + RAILS_ENV == "development" + end + + def choose_layout + # This ivar could be set by some form of site config later + @layout ||= "twibblr" + end + end +end \ No newline at end of file diff --git a/app/controllers/twibblr/posts_controller.rb b/app/controllers/twibblr/posts_controller.rb new file mode 100644 index 0000000..b7caa56 --- /dev/null +++ b/app/controllers/twibblr/posts_controller.rb @@ -0,0 +1,43 @@ +module Twibblr + class PostsController < BaseController + before_filter :filter_by_time, :only => [:index, :show] + + def index + @posts = @posts.all + respond_to do |format| + format.html + format.rss { render :layout => false } + end + end + + def by_tag + @posts = Tag.find_by_permalink(params[:tag]).posts + render :index + rescue + flash[:error] = "Tag '#{params[:tag]}' does not exist." + redirect_to :action => :index + end + + def show + @post = @posts.find(params[:id].to_i, :include => :comments) + + @comments = @post.comments + @comment = Comment.new + + respond_to do |format| + format.html # show.html.erb + format.rss { render :layout => false } + end + end + + protected + + # TODO: this needs to be cleaner!!! + def filter_by_time + @posts = Post + @posts = @posts.in_year(params[:year]) if params[:year] + @posts = @posts.in_month(params[:month]) if params[:month] + @posts = @posts.in_day(params[:day]) if params[:day] + end + end +end \ No newline at end of file diff --git a/app/controllers/twibblr_controller.rb b/app/controllers/twibblr_controller.rb deleted file mode 100644 index 2826949..0000000 --- a/app/controllers/twibblr_controller.rb +++ /dev/null @@ -1,17 +0,0 @@ -# Define a master controller for plugin to have defaults set everywhere -class TwibblrController < ApplicationController - helper :twibblr - filter_parameter_logging :password - layout :choose_layout - - protected - - def development? - RAILS_ENV == "development" - end - - def choose_layout - # This ivar could be set by some form of site config later - @layout ||= "twibblr" - end -end \ No newline at end of file diff --git a/app/helpers/twibblr_helper.rb b/app/helpers/twibblr_helper.rb index 42db40f..6414106 100644 --- a/app/helpers/twibblr_helper.rb +++ b/app/helpers/twibblr_helper.rb @@ -1,38 +1,38 @@ module TwibblrHelper def render_posts(*args, &block) # if they are fetching posts in the controller # then awesome(!) otherwise get it for them - posts = @posts || Post.all(*args) + posts = @posts || Twibblr::Post.all(*args) if block_given? posts.each do |post| render_post(post, &block) end else render :partial => posts end end def render_tags(*args) raise "No Block Given" unless block_given? options = {:order => "name"}.merge(args.extract_options!) args << options - (@tags || Tag.all(*args)).each {|tag| yield(tag)} + (@tags || Twibblr::Tag.all(*args)).each {|tag| yield(tag)} end private def render_post(post, &block) raise "No block given" unless block_given? case block.arity when 1 then yield(post) when 2 then yield(post.title, post.body) when 3 then yield(post.title, post.body, post.created_at) when 4 then yield(post.title, post.body, post.created_at, post.tags) when 5 then yield(post.title, post.body, post.created_at, post.tags, post.comments) else raise "Parameter Error" end end end \ No newline at end of file diff --git a/app/models/comment.rb b/app/models/twibblr/comment.rb similarity index 58% rename from app/models/comment.rb rename to app/models/twibblr/comment.rb index d1e9de1..b400b89 100644 --- a/app/models/comment.rb +++ b/app/models/twibblr/comment.rb @@ -1,4 +1,4 @@ -class Comment < ActiveRecord::Base +class Twibblr::Comment < ActiveRecord::Base belongs_to :post validates_presence_of :name, :email end diff --git a/app/models/post.rb b/app/models/twibblr/post.rb similarity index 94% rename from app/models/post.rb rename to app/models/twibblr/post.rb index 97d0401..f396a88 100644 --- a/app/models/post.rb +++ b/app/models/twibblr/post.rb @@ -1,36 +1,36 @@ -class Post < ActiveRecord::Base +class Twibblr::Post < ActiveRecord::Base default_scope :order => "created_at DESC" has_many :comments, :order => "created_at ASC" has_many :posts_tags has_many :tags, :through => :posts_tags, :order => "name ASC" named_scope :archive, :group => "month(created_at)" validates_presence_of :body, :title %w{year month day}.each do |time| delegate time, :to => :created_at named_scope :"in_#{time}", lambda { |num| {:conditions => ["#{time.upcase}(created_at) = ?", num] } } end def date created_at.to_date.to_s(:long_ordinal) end def to_s title end def link @link ||= "/#{created_at.year}/#{created_at.month}/#{created_at.day}/#{to_param}" end def to_param if title.blank? id else "#{id}-#{title.parameterize}" end end end \ No newline at end of file diff --git a/app/models/posts_tag.rb b/app/models/twibblr/posts_tag.rb similarity index 59% rename from app/models/posts_tag.rb rename to app/models/twibblr/posts_tag.rb index c5c1fe6..c83d8ee 100644 --- a/app/models/posts_tag.rb +++ b/app/models/twibblr/posts_tag.rb @@ -1,4 +1,4 @@ -class PostsTag < ActiveRecord::Base +class Twibblr::PostsTag < ActiveRecord::Base belongs_to :post belongs_to :tag, :counter_cache => "posts_count" end \ No newline at end of file diff --git a/app/models/tag.rb b/app/models/twibblr/tag.rb similarity index 93% rename from app/models/tag.rb rename to app/models/twibblr/tag.rb index 448b86f..2902cc4 100644 --- a/app/models/tag.rb +++ b/app/models/twibblr/tag.rb @@ -1,33 +1,33 @@ -class Tag < ActiveRecord::Base +class Twibblr::Tag < ActiveRecord::Base default_scope :order => "posts_count" has_many :posts_tags has_many :posts, :through => :posts_tags, :order => "created_at ASC" before_create :set_permalink before_save :lowercase_name def to_s name end def to_param permalink end def self.[](identifier) identifier.is_a?(Fixnum) ? find(identifier) : find(:first, :conditions => ["name = :name OR permalink = :name", {:name => identifier.to_s}]) rescue nil end private def set_permalink self.permalink = name.parameterize if permalink.blank? end def lowercase_name self.name.downcase! end end \ No newline at end of file diff --git a/app/views/posts/_post.html.erb b/app/views/twibblr/posts/_post.html.erb similarity index 100% rename from app/views/posts/_post.html.erb rename to app/views/twibblr/posts/_post.html.erb diff --git a/app/views/posts/index.html.erb b/app/views/twibblr/posts/index.html.erb similarity index 100% rename from app/views/posts/index.html.erb rename to app/views/twibblr/posts/index.html.erb diff --git a/app/views/posts/index.rss.builder b/app/views/twibblr/posts/index.rss.builder similarity index 100% rename from app/views/posts/index.rss.builder rename to app/views/twibblr/posts/index.rss.builder diff --git a/app/views/posts/show.html.erb b/app/views/twibblr/posts/show.html.erb similarity index 100% rename from app/views/posts/show.html.erb rename to app/views/twibblr/posts/show.html.erb diff --git a/config/initializers/mime_types.rb b/config/initializers/mime_types.rb deleted file mode 100644 index 96a1add..0000000 --- a/config/initializers/mime_types.rb +++ /dev/null @@ -1,5 +0,0 @@ -# TODO - make sure it doesn't overwrite existing mime types -Mime::Type.register "image/jpeg", :jpg -Mime::Type.register "image/jpeg", :jpeg -Mime::Type.register "image/gif", :gif -Mime::Type.register "image/png", :png diff --git a/config/routes.rb b/config/routes.rb index 02dd290..ed7da71 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,26 +1,26 @@ YEAR_REGEX = /\d{4}/ MONTH_REGEX = /(?:0?[1-9]|1[012])/ DAY_REGEX = /(?:0?[1-9]|[12][0-9]|3[01])/ PARAM_REGEX = /\d+(?:-[a-z0-9_-]+?)?/ ActionController::Routing::Routes.draw do |map| map.with_options :conditions => {:method => :get} do |get| - get.with_options :controller => "posts" do |posts| + get.with_options :controller => "twibblr/posts" do |posts| posts.with_options :action => "index" do |list_posts| list_posts.root list_posts.posts "/posts" list_posts.formatted_posts "/posts.:format" list_posts.map "/:year", :requirements => {:year => YEAR_REGEX} list_posts.map "/:year/:month", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX} list_posts.map "/:year/:month/:day", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX, :day => DAY_REGEX} end posts.map "/tags/:tag", :action => "by_tag" options = {:action => "show", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX, :day => DAY_REGEX, :id => PARAM_REGEX}} posts.post "/:year/:month/:day/:id", options posts.formatted_post "/:year/:month/:day/:id.:format", options end end -end +end \ No newline at end of file diff --git a/init.rb b/init.rb index 93b6e72..9635da9 100644 --- a/init.rb +++ b/init.rb @@ -1,10 +1,12 @@ # We want to reload all the controllers, helpers, and # models if we are in development mode: ActiveSupport::Dependencies.load_once_paths.clear if RAILS_ENV == "development" -::TWIBBLR_ROOT = File.expand_path(File.dirname(__FILE__)) +module Twibblr + ROOT = File.expand_path(File.dirname(__FILE__)) +end # Load plug-in initializers -Dir.chdir(File.join(::TWIBBLR_ROOT, "config", "initializers")) do +Dir.chdir(File.join(Twibblr::ROOT, "config", "initializers")) do Dir["*.rb"].each { |file| require file } end \ No newline at end of file
bjeanes/twibblr
59155f2a746c631845bf91b7c18f2066122bd4dc
Fixed paths
diff --git a/app/views/layouts/twibblr.html.erb b/app/views/layouts/twibblr.html.erb index aad3f8a..8d72def 100644 --- a/app/views/layouts/twibblr.html.erb +++ b/app/views/layouts/twibblr.html.erb @@ -1,64 +1,64 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>My website - powered by Twibblr</title> <meta name="keywords" content="" /> <meta name="description" content="" /> - <link href="/twibblr/master.css" rel="stylesheet" type="text/css" media="screen" /> + <link href="/twibblr/stylesheets/master.css" rel="stylesheet" type="text/css" media="screen" /> <%= yield :head %> </head> <body> <!-- start header --> <div id="header"> <div id="logo"> <h1><%= link_to "My Website", "/" %></h1> <p>Powered by <a href="http://github.com/bjeanes/twibblr">Twibblr</a></p> </div> <div id="search"> <form method="get" action=""> <fieldset> <input id="s" type="text" name="s" value="" /> <input id="x" type="submit" value="Search" /> </fieldset> </form> </div> </div> <!-- end header --> <!-- start page --> <div id="page"> <!-- start content --> <div id="content"> <%= yield %> </div> <!-- end content --> <!-- start sidebar --> <div id="sidebar"> <ul> <li> <h2>Updates:</h2> <ul> <% render_posts(:limit => 5) do |post| %> <li><%= link_to post.title, post.link %></li> <% end %> </ul> </li> <li> <h2>Tags</h2> <ul> <% render_tags do |tag| %> <li><%= link_to "#{tag} (#{tag.posts_count})", "/tags/#{tag.permalink}" %></li> <% end %> </ul> </li> </ul> </div> <!-- end sidebar --> </div> <!-- end page --> <div id="footer"> <p>&copy;2007 All Rights Reserved. &nbsp;&bull;&nbsp; Design by <a href="http://templatefusion.org">TemplateFusion</a> &nbsp;&bull;&nbsp; Icons by <a href="http://www.famfamfam.com/">FAMFAMFAM</a>.</p> </div> </body> </html> \ No newline at end of file diff --git a/public/stylesheets/master.css b/public/stylesheets/master.css index 5f7accd..81c89f3 100644 --- a/public/stylesheets/master.css +++ b/public/stylesheets/master.css @@ -1,395 +1,395 @@ /* Design by TemplateFusion http://templatefusion.org Released for free under a Creative Commons Attribution 2.5 Canada License */ body { margin: 0; padding: 0; - background: #FFFFFF url(/twibblr/img01.jpg) repeat-x; + background: #FFFFFF url(../images/img01.jpg) repeat-x; font-size: 13px; color: #666666; } body, th, td, input, textarea, select, option { font-family: Arial, Helvetica, sans-serif; } h1, h2, h3 { font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; color:#666666; } h1 { letter-spacing: -2px; font-size: 3em; } h2 { letter-spacing: -1px; font-size: 2em; } h3 { font-size: 1em; } p, ul, ol { line-height: 200%; } img { border: 0px; } a { color: #333333; } a:hover { text-decoration: none; } /* Header */ #header { width: 760px; height: 200px; margin: 0 auto; - background: url(/twibblr/img02.jpg) no-repeat left center; + background: url(../images/img02.jpg) no-repeat left center; } #logo { float: left; padding: 90px 0 0 0; } #logo h1, #logo p { margin: 0; color: #FFFFFF; padding-left: 60px; } #logo a { color: #FFFFFF; } #search { float: right; width: 200px; padding: 135px 0 0 0; } #search form { margin: 0; padding: 0; } #search fieldset { margin: 0; padding: 0; border: none; } #s { width: 190px; padding: 3px 5px; - background: #FFFFFF url(/twibblr/img03.gif) repeat-x; + background: #FFFFFF url(../images/img03.gif) repeat-x; border: 1px solid #FFFFFF; } #x { display: none; } /* Page */ #page { width: 720px; margin: 0 auto; padding: 20px 0; } /* Content */ #content { float: right; width: 420px; } .post { padding: 0 0 20px 0; } .title { margin: 0; } .byline { margin: 0; } .meta { padding: 5px 10px; border: 1px solid #EFEFEF; background: #F9F9F9; } .meta .more { padding-left: 20px; - background: url(/twibblr/img04.gif) no-repeat left center; + background: url(../images/img04.gif) no-repeat left center; } .meta .comments { padding-left: 20px; - background: url(/twibblr/img05.gif) no-repeat left center; + background: url(../images/img05.gif) no-repeat left center; } /* Sidebar */ #sidebar { float: left; width: 240px; } #sidebar ul { margin: 0; padding: 0; list-style: none; } #sidebar li { } #sidebar li ul { } #sidebar li li { padding-left: 10px; - background: url(/twibblr/img06.gif) no-repeat left center; + background: url(../images/img06.gif) no-repeat left center; border-bottom: 1px dotted #CCCCCC; } #sidebar h2 { margin: 0; padding: 20px 0; } #sidebar a { text-decoration: none; } #sidebar a:hover { color: #999999; } /* Footer */ #footer { clear: both; padding: 30px 0; - background: url(/twibblr/img07.gif) repeat-x; + background: url(../images/img07.gif) repeat-x; text-align: center; font-size: smaller; } /* Special Formatting */ code { margin: 5px 0; padding: 10px; text-align: left; display: block; overflow: auto; font: 500 1em/1.5em 'Lucida Console', 'courier new', monospace; /* white-space: pre; */ background: #FAFAFA; border: 1px solid #f2f2f2; border-left: 3px solid #999999; } blockquote { margin: 15px; padding: 0 0 0 20px; background-color: #FAFAFA; background-position: 8px 10px; border: 1px solid #f2f2f2; border-left: 3px solid #999999; font: bold 1.2em/1.5em "Trebuchet MS", Tahoma, sans-serif; color: #666666; } blockquote p, blockquote ul, blockquote ol { line-height: normal; font-style: italic; } .float-left { float: left; padding-right: 5px; } .float-right { float: right; padding-left: 5px; } .align-left { text-align: left; } .align-right { text-align: right; } /* Table Styling */ table { border-collapse: collapse; margin: 10px 15px; } th strong { color: #fff; } th { background: #717170; - background-image:url(/twibblr/table-bg.jpg); background-repeat:repeat-x; + background-image:url(../images/table-bg.jpg); background-repeat:repeat-x; height: 29px; padding-left: 11px; padding-right: 11px; color: #fff; text-align: left; border-left: 1px solid #999999; border-bottom: solid 2px #FFF; } tr { height: 30px; } td { padding-left: 11px; padding-right: 11px; /* border-left: 1px solid #FFE1C3; */ border-left: 1px solid #FFF; border-bottom: solid 1px #ffffff; } td.first,th.first { border-left: 0px; } tr.row-a { background: #F8F8F8; } tr.row-b { background: #EFEFEF; } /* form styling */ form { margin:10px 15px; padding: 5px; border: 1px solid #EEEEEE; background-color: #FAFAFA; } label { display:block; font-weight:bold; margin:5px 0; } input { width: 275px; padding: 2px; border:1px solid #eee; font: normal 1em "Trebuchet MS", Tahoma, sans-serif; color:#777; } textarea { width:375px; padding:2px; font: normal 1em "Trebuchet MS", Tahoma, sans-serif; border:1px solid #eee; height:100px; display:block; color:#777; } input.button { margin: 0; font: bold 1em Arial, Sans-serif; background: #FFF url(gradientbg.jpg) repeat-x; padding: 2px 3px; color: #333; border: 1px solid #DADADA; } \ No newline at end of file
bjeanes/twibblr
d1f930e4808aa1d193886d3a62bf1b5eddb0b840
Delete no longer used files from the twibblr directly on install
diff --git a/tasks/install.rake b/tasks/install.rake index 2bf5add..9f17460 100644 --- a/tasks/install.rake +++ b/tasks/install.rake @@ -1,7 +1,7 @@ namespace :twibblr do task :install do # From railscasts #149 system "rsync -ruv vendor/plugins/twibblr/db/migrate db" - system "rsync -ruv vendor/plugins/twibblr/public public/twibblr" + system "rsync -ruv --delete vendor/plugins/twibblr/public/ public/twibblr" end end
bjeanes/twibblr
a5a987e486637ef045401a5302a758bd31a7af1c
Just RSync'ing files instead of AssetsController hackery
diff --git a/app/controllers/assets_controller.rb b/app/controllers/assets_controller.rb deleted file mode 100644 index 3acb05e..0000000 --- a/app/controllers/assets_controller.rb +++ /dev/null @@ -1,43 +0,0 @@ -class AssetsController < TwibblrController - layout nil - around_filter :asset_check - - PUBLIC_DIR = File.join(::TWIBBLR_ROOT, 'public') - - def stylesheet - respond_to { |format| format.css { send_file(File.join(PUBLIC_DIR, 'stylesheets', "#{params[:stylesheet]}.css"), :type => "text/css") } } - end - - def javascript - respond_to { |format| format.js { send_file(File.join(PUBLIC_DIR, 'javascripts', "#{params[:javascript]}.js"), :type => "text/javascript") } } - end - - def image - respond_to do |format| - %w{gif png jpg}.each do |f| - format.send(f) do - image = File.expand_path(File.join(PUBLIC_DIR, 'images', "#{params[:image]}.#{f}")) - send_file(image) and return - end - end - end - end - - protected - - def asset_check - if file_safe? - yield - else - raise "unsafe file" - end - rescue - raise ActiveRecord::RecordNotFound unless development? - end - - # TODO make these check the params to make sure we aren't - # accessing arbitrary files on the system etc - def file_safe? - true - end -end \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 770946f..02dd290 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,35 +1,26 @@ YEAR_REGEX = /\d{4}/ MONTH_REGEX = /(?:0?[1-9]|1[012])/ DAY_REGEX = /(?:0?[1-9]|[12][0-9]|3[01])/ PARAM_REGEX = /\d+(?:-[a-z0-9_-]+?)?/ ActionController::Routing::Routes.draw do |map| map.with_options :conditions => {:method => :get} do |get| get.with_options :controller => "posts" do |posts| posts.with_options :action => "index" do |list_posts| list_posts.root list_posts.posts "/posts" list_posts.formatted_posts "/posts.:format" list_posts.map "/:year", :requirements => {:year => YEAR_REGEX} list_posts.map "/:year/:month", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX} list_posts.map "/:year/:month/:day", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX, :day => DAY_REGEX} end posts.map "/tags/:tag", :action => "by_tag" options = {:action => "show", :requirements => {:year => YEAR_REGEX, :month => MONTH_REGEX, :day => DAY_REGEX, :id => PARAM_REGEX}} posts.post "/:year/:month/:day/:id", options posts.formatted_post "/:year/:month/:day/:id.:format", options end - - get.with_options :controller => "assets" do |assets| -# assets.connect "/twibblr" - assets.connect "/twibblr/:stylesheet.css", :action => "stylesheet" - assets.connect "/twibblr/:javascript.js", :action => "javascript" - %w{jpg png gif jpeg}.each do |ext| - assets.connect "/twibblr/:image.#{ext}", :action => "image" - end - end end end diff --git a/tasks/install.rake b/tasks/install.rake new file mode 100644 index 0000000..2bf5add --- /dev/null +++ b/tasks/install.rake @@ -0,0 +1,7 @@ +namespace :twibblr do + task :install do + # From railscasts #149 + system "rsync -ruv vendor/plugins/twibblr/db/migrate db" + system "rsync -ruv vendor/plugins/twibblr/public public/twibblr" + end +end diff --git a/tasks/plugin/twibblr/copy_migrations.rake b/tasks/plugin/twibblr/copy_migrations.rake deleted file mode 100644 index fad0495..0000000 --- a/tasks/plugin/twibblr/copy_migrations.rake +++ /dev/null @@ -1,38 +0,0 @@ -TWIBBLR_ROOT = File.expand_path(File.join(File.dirname(__FILE__),'..','..','..')) - -def db_migrate_path(root) - File.join(root, "db", "migrate") -end - -def migrations(path) - Dir.chdir(path) do - Dir["*.rb"].sort - end -end - -namespace :plugin do - namespace :twibblr do - desc "Copy Twibblr migrations to db/migrate" - task :copy_migrations do - app_migrate_path = db_migrate_path(RAILS_ROOT) - plugin_migrate_path = db_migrate_path(TWIBBLR_ROOT) - - app_migrations = migrations(app_migrate_path) - plugin_migrations = migrations(plugin_migrate_path) - - time = Time.now - - plugin_migrations.each do |migration| - migration_name = migration.match(/\d+_(.+)\.rb/)[1].to_s - - if app_migrations.grep(Regexp.new("#{migration_name}\.rb$")).empty? - new_migration = "#{(time+=1).to_s(:number)}_#{migration_name}.rb" - source = File.join(plugin_migrate_path, migration) - destination = File.join(app_migrate_path, new_migration) - puts "Installing #{migration} into main Rails application" - FileUtils.cp(source, destination) - end - end - end - end -end \ No newline at end of file
bjeanes/twibblr
6b365115ffc9315bad76f64daa087e74746d57a6
Made a few links for navigation for demo purposes
diff --git a/app/views/layouts/twibblr.html.erb b/app/views/layouts/twibblr.html.erb index e2f6906..aad3f8a 100644 --- a/app/views/layouts/twibblr.html.erb +++ b/app/views/layouts/twibblr.html.erb @@ -1,64 +1,64 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> - <title>Sleek by TemplateFusion.org</title> + <title>My website - powered by Twibblr</title> <meta name="keywords" content="" /> <meta name="description" content="" /> <link href="/twibblr/master.css" rel="stylesheet" type="text/css" media="screen" /> <%= yield :head %> </head> <body> <!-- start header --> <div id="header"> <div id="logo"> - <h1>My Website</h1> + <h1><%= link_to "My Website", "/" %></h1> <p>Powered by <a href="http://github.com/bjeanes/twibblr">Twibblr</a></p> </div> <div id="search"> <form method="get" action=""> <fieldset> <input id="s" type="text" name="s" value="" /> <input id="x" type="submit" value="Search" /> </fieldset> </form> </div> </div> <!-- end header --> <!-- start page --> <div id="page"> <!-- start content --> <div id="content"> <%= yield %> </div> <!-- end content --> <!-- start sidebar --> <div id="sidebar"> <ul> <li> <h2>Updates:</h2> <ul> <% render_posts(:limit => 5) do |post| %> <li><%= link_to post.title, post.link %></li> <% end %> </ul> </li> <li> <h2>Tags</h2> <ul> <% render_tags do |tag| %> <li><%= link_to "#{tag} (#{tag.posts_count})", "/tags/#{tag.permalink}" %></li> <% end %> </ul> </li> </ul> </div> <!-- end sidebar --> </div> <!-- end page --> <div id="footer"> <p>&copy;2007 All Rights Reserved. &nbsp;&bull;&nbsp; Design by <a href="http://templatefusion.org">TemplateFusion</a> &nbsp;&bull;&nbsp; Icons by <a href="http://www.famfamfam.com/">FAMFAMFAM</a>.</p> </div> </body> </html> \ No newline at end of file diff --git a/app/views/posts/_post.html.erb b/app/views/posts/_post.html.erb index 866869b..fa913e4 100644 --- a/app/views/posts/_post.html.erb +++ b/app/views/posts/_post.html.erb @@ -1,12 +1,12 @@ <div class="post"> - <h1 class="title"><%= post.title.titleize %></h1> + <h1 class="title"><%= link_to post.title.titleize, post.link %></h1> <p class="byline"><small>Posted on <%= post.created_at.strftime("%B %d, %Y") %> | <a href="#">Edit Post</a></small></p> <div class="entry"> <% if controller.action_name == "show" %> <%= simple_format(post.body) %> <% else %> <%= truncate(simple_format(post.body), 250, ' ... (continued)') %> <% end %> </div> <p class="meta"><a href="#" class="more">Read More</a> &nbsp;&nbsp;&nbsp; <a href="#" class="comments">Comments (1337)</a></p> </div> \ No newline at end of file
bjeanes/twibblr
e2bbfb0ce970ef7719a61e4f697460c615dacda3
made tag viewing work (loads index action)
diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rb index 9d233d9..3dd0981 100644 --- a/app/controllers/posts_controller.rb +++ b/app/controllers/posts_controller.rb @@ -1,40 +1,41 @@ class PostsController < TwibblrController before_filter :filter_by_time, :only => [:index, :show] def index @posts = @posts.all respond_to do |format| format.html format.rss { render :layout => false } end end def by_tag @posts = Tag.find_by_permalink(params[:tag]).posts + render :index rescue flash[:error] = "Tag '#{params[:tag]}' does not exist." redirect_to :action => :index end def show @post = @posts.find(params[:id].to_i, :include => :comments) @comments = @post.comments @comment = Comment.new respond_to do |format| format.html # show.html.erb format.rss { render :layout => false } end end protected # TODO: this needs to be cleaner!!! def filter_by_time @posts = Post @posts = @posts.in_year(params[:year]) if params[:year] @posts = @posts.in_month(params[:month]) if params[:month] @posts = @posts.in_day(params[:day]) if params[:day] end end \ No newline at end of file