Class: FeedTools::FeedUpdater
- Inherits:
-
Object
- Object
- FeedTools::FeedUpdater
- Defined in:
- lib/feed_updater.rb
Overview
A simple daemon for scheduled updating of feeds.
Class Method Summary collapse
-
.on_begin(&block) ⇒ Object
Declares an on_begin event.
-
.on_complete(&block) ⇒ Object
Declares an on_complete event.
-
.on_error(&block) ⇒ Object
Declares an on_error event.
-
.on_update(&block) ⇒ Object
Declares an on_update event.
Instance Method Summary collapse
-
#application ⇒ Object
Returns a reference to the daemon application.
-
#daemon_options ⇒ Object
Returns a hash of the currently set daemon options.
-
#feed_href_list ⇒ Object
Returns a list of feeds to be updated.
-
#feed_href_list=(new_feed_href_list) ⇒ Object
Sets a list of feeds to be updated.
-
#initial_directory ⇒ Object
Returns the initial directory that the daemon was started from.
-
#log_file ⇒ Object
Returns the path to the log file.
-
#log_file_dir ⇒ Object
Returns the directory where the log files are stored.
-
#log_file_dir=(new_log_file_dir) ⇒ Object
Sets the directory where the log files are stored.
-
#logger ⇒ Object
Returns the logger object.
-
#pid ⇒ Object
Returns the process id of the daemon.
-
#pid_file_dir ⇒ Object
Returns the directory where the pid files are stored.
-
#pid_file_dir=(new_pid_file_dir) ⇒ Object
Sets the directory where the pid files are stored.
- #progress_precentage ⇒ Object
-
#restart ⇒ Object
Restarts the daemon.
-
#restart_logger ⇒ Object
Restarts the logger object.
-
#start ⇒ Object
Starts the daemon.
-
#status ⇒ Object
Returns either :running or :stopped depending on the daemon’s current status.
-
#stop ⇒ Object
Stops the daemon.
-
#update_feeds ⇒ Object
Updates all of the feeds.
-
#updater_options ⇒ Object
Returns a hash of the currently set updater options.
Class Method Details
.on_begin(&block) ⇒ Object
Declares an on_begin event. The given block will be called before the update sequence runs to allow for any setup required. The block is not passed any arguments.
124 125 126 127 |
# File 'lib/feed_updater.rb', line 124 def self.on_begin(&block) raise "No block supplied for on_begin." if block.nil? @@on_begin = block end |
.on_complete(&block) ⇒ Object
Declares an on_complete event. The given block will be called after all feeds have been updated. The block is passed a list of feeds that FeedUpdater attempted to update.
148 149 150 151 |
# File 'lib/feed_updater.rb', line 148 def self.on_complete(&block) raise "No block supplied for on_complete." if block.nil? @@on_complete = block end |
.on_error(&block) ⇒ Object
Declares an on_error event. The given block will be called after an error occurs during a feed update. The block is passed the href of the feed that errored out, and the exception object that was raised.
140 141 142 143 |
# File 'lib/feed_updater.rb', line 140 def self.on_error(&block) raise "No block supplied for on_error." if block.nil? @@on_error = block end |
.on_update(&block) ⇒ Object
Declares an on_update event. The given block will be called after every feed update. The block is passed the feed object that was loaded and the time it took in seconds to successfully load it.
132 133 134 135 |
# File 'lib/feed_updater.rb', line 132 def self.on_update(&block) raise "No block supplied for on_update." if block.nil? @@on_update = block end |
Instance Method Details
#application ⇒ Object
Returns a reference to the daemon application.
277 278 279 280 |
# File 'lib/feed_updater.rb', line 277 def application() @application = nil if !defined?(@application) return @application end |
#daemon_options ⇒ Object
Returns a hash of the currently set daemon options.
262 263 264 265 266 267 268 269 270 271 272 273 274 |
# File 'lib/feed_updater.rb', line 262 def () if !defined?(@daemon_options) || @daemon_options.nil? @daemon_options = { :app_name => "feed_updater_daemon", :dir_mode => :normal, :dir => self.pid_file_dir, :backtrace => true, :ontop => false } end @daemon_options[:dir] = self.pid_file_dir return @daemon_options end |
#feed_href_list ⇒ Object
Returns a list of feeds to be updated.
221 222 223 224 225 226 227 228 229 230 231 232 233 |
# File 'lib/feed_updater.rb', line 221 def feed_href_list() if !defined?(@feed_href_list) || @feed_href_list.nil? @feed_href_list_override = false if self..nil? @feed_href_list = nil elsif self.[:feed_href_list].kind_of?(Array) @feed_href_list = self.[:feed_href_list] else @feed_href_list = nil end end return @feed_href_list end |
#feed_href_list=(new_feed_href_list) ⇒ Object
Sets a list of feeds to be updated.
236 237 238 239 |
# File 'lib/feed_updater.rb', line 236 def feed_href_list=(new_feed_href_list) @feed_href_list_override = true @feed_href_list = new_feed_href_list end |
#initial_directory ⇒ Object
Returns the initial directory that the daemon was started from.
154 155 156 157 |
# File 'lib/feed_updater.rb', line 154 def initial_directory() @initial_directory = nil if !defined?(@initial_directory) return @initial_directory end |
#log_file ⇒ Object
Returns the path to the log file.
182 183 184 185 186 187 188 189 190 191 192 |
# File 'lib/feed_updater.rb', line 182 def log_file() if !defined?(@log_file) || @log_file.nil? if self.log_file_dir.nil? @log_file = File.("./feed_updater.log") else @log_file = File.( self.log_file_dir + "/feed_updater.log") end end return @log_file end |
#log_file_dir ⇒ Object
Returns the directory where the log files are stored.
171 172 173 174 |
# File 'lib/feed_updater.rb', line 171 def log_file_dir() @log_file_dir = nil if !defined?(@log_file_dir) return @log_file_dir end |
#log_file_dir=(new_log_file_dir) ⇒ Object
Sets the directory where the log files are stored.
177 178 179 |
# File 'lib/feed_updater.rb', line 177 def log_file_dir=(new_log_file_dir) @log_file_dir = new_log_file_dir end |
#logger ⇒ Object
Returns the logger object.
195 196 197 198 199 200 201 202 203 204 |
# File 'lib/feed_updater.rb', line 195 def logger() if !defined?(@logger) || @logger.nil? @logger = FeedUpdaterLogger.new(self.log_file) @logger.level = self.[:log_level] @logger.datetime_format = nil @logger.progname = nil @logger.prefix = "FeedUpdater".ljust(20) end return @logger end |
#pid ⇒ Object
Returns the process id of the daemon. This should return nil if the daemon is not running.
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 |
# File 'lib/feed_updater.rb', line 284 def pid() if File.exists?(File.(pid_file_dir + "/feed_updater.pid")) begin pid_file = File.open( File.(pid_file_dir + "/feed_updater.pid"), "r") return pid_file.read.to_s.strip.to_i rescue Exception return nil end else return nil if self.application.nil? begin return self.application.pid.pid rescue Exception return nil end end end |
#pid_file_dir ⇒ Object
Returns the directory where the pid files are stored.
160 161 162 163 |
# File 'lib/feed_updater.rb', line 160 def pid_file_dir() @pid_file_dir = nil if !defined?(@pid_file_dir) return @pid_file_dir end |
#pid_file_dir=(new_pid_file_dir) ⇒ Object
Sets the directory where the pid files are stored.
166 167 168 |
# File 'lib/feed_updater.rb', line 166 def pid_file_dir=(new_pid_file_dir) @pid_file_dir = new_pid_file_dir end |
#progress_precentage ⇒ Object
518 519 520 521 522 523 524 525 526 527 528 529 530 |
# File 'lib/feed_updater.rb', line 518 def progress_precentage() if !defined?(@remaining_href_list) || !defined?(@feed_href_list) return nil end if @remaining_href_list.nil? || @feed_href_list.nil? return nil end if @feed_href_list == [] return nil end return 100.0 - (100.0 * (@remaining_href_list.size.to_f / @feed_href_list.size.to_f)) end |
#restart ⇒ Object
Restarts the daemon.
513 514 515 516 |
# File 'lib/feed_updater.rb', line 513 def restart() self.stop() self.start() end |
#restart_logger ⇒ Object
Restarts the logger object. This needs to be done after the program forks.
208 209 210 211 212 213 214 215 216 217 218 |
# File 'lib/feed_updater.rb', line 208 def restart_logger() begin self.logger.close() rescue IOError end @logger = FeedUpdaterLogger.new(self.log_file) @logger.level = self.[:log_level] @logger.datetime_format = nil @logger.progname = nil @logger.prefix = "FeedUpdater".ljust(20) end |
#start ⇒ Object
Starts the daemon.
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 |
# File 'lib/feed_updater.rb', line 314 def start() self.logger.prefix = "FeedUpdater".ljust(20) if !defined?(@@on_update) || @@on_update.nil? raise "No on_update handler block given." end if self.status == :running || self.pid != nil puts "FeedUpdater is already running." return self.pid end if defined?(ActiveRecord) ActiveRecord::Base.allow_concurrency = true end @initial_directory = File.(".") if @application.nil? self.logger() feed_update_proc = lambda do # Reestablish correct location Dir.chdir(File.(self.initial_directory)) sleep(1) self.restart_logger() self.logger.info("Using environment: #{FEED_TOOLS_ENV}") if FeedTools.configurations[:feed_cache].nil? FeedTools.configurations[:feed_cache] = "FeedTools::DatabaseFeedCache" end if !FeedTools.feed_cache.connected? FeedTools.configurations[:feed_cache] = "FeedTools::DatabaseFeedCache" FeedTools.feed_cache.initialize_cache() begin ActiveRecord::Base.default_timezone = :utc ActiveRecord::Base.connection rescue Exception config_path = FileStalker.hunt([ "./config/database.yml", "../config/database.yml", "../../config/database.yml", "./database.yml", "../database.yml", "../../database.yml" ]) if config_path != nil require 'yaml' config_hash = File.open(config_path) do |file| config_hash = YAML.load(file.read) unless config_hash[FEED_TOOLS_ENV].nil? config_hash = config_hash[FEED_TOOLS_ENV] end config_hash end self.logger.info( "Attempting to manually load the database " + "connection described in:") self.logger.info(config_path) begin ActiveRecord::Base.configurations = config_hash ActiveRecord::Base.establish_connection(config_hash) ActiveRecord::Base.connection rescue Exception => error self.logger.fatal( "Error initializing database:") self.logger.fatal(error) exit end else self.logger.fatal( "The database.yml file does not appear " + "to exist.") exit end end end if !FeedTools.feed_cache.connected? self.logger.fatal("Not connected to the feed cache.") if FeedTools.feed_cache.respond_to?(:table_exists?) if !FeedTools.feed_cache.table_exists? self.logger.fatal( "The FeedTools cache table is missing.") end end exit end # A random start delay is introduced so that we don't have multiple # feed updater daemons getting kicked off at the same time by # multiple users. if self.[:start_delay] delay = (rand(45) + 15) self.logger.info("Startup delay set for #{delay} minutes.") sleep(delay.minutes) end # The main feed update loop. loop do result = nil sleepy_time = self.[:sleep_time].to_i.minutes begin result = Benchmark.measure do self.update_feeds() end self.logger.info( "#{@feed_href_list.size} feed(s) updated " + "in #{result.real.round} seconds.") sleepy_time = (self.[:sleep_time].to_i.minutes - result.real.round) rescue Exception => error self.logger.error("Feed update sequence errored out.") self.logger.error(error.class.name + ": " + error.) self.logger.error("\n" + error.backtrace.join("\n").to_s) end @feed_href_list = nil @feed_href_list_override = false ObjectSpace.garbage_collect() if sleepy_time > 0 self.logger.info( "Sleeping for #{(sleepy_time / 1.minute.to_f).round} " + "minutes...") sleep(sleepy_time) else self.logger.info( "Update took more than " + "#{self.[:sleep_time].to_i} minutes, " + "restarting immediately.") end end end = self..merge({ :proc => feed_update_proc, :mode => :proc }) @application = Daemons::ApplicationGroup.new( 'feed_updater', ).new_application() @application.start() else @application.start() end self.logger.prefix = nil self.logger.level = 0 self.logger.info("-" * 79) self.logger.info("Daemon started, " + "FeedUpdater #{FeedTools::FEED_UPDATER_VERSION::STRING} / " + "FeedTools #{FeedTools::FEED_TOOLS_VERSION::STRING}") self.logger.info(" @ #{Time.now.utc.to_s}") self.logger.info("-" * 79) self.logger.level = self.[:log_level] self.logger.prefix = "FeedUpdater".ljust(20) @status = :running return self.pid end |
#status ⇒ Object
Returns either :running or :stopped depending on the daemon’s current status.
243 244 245 246 |
# File 'lib/feed_updater.rb', line 243 def status() @status = :stopped if @status.nil? return @status end |
#stop ⇒ Object
Stops the daemon.
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 |
# File 'lib/feed_updater.rb', line 473 def stop() if self.pid.nil? puts "FeedUpdater isn't running." end begin # Die. Process.kill('TERM', self.pid) rescue Exception end begin # No, really, I mean it. You need to die. system("kill #{self.pid} 2> /dev/null") # Perhaps I wasn't clear somehow? system("kill -9 #{self.pid} 2> /dev/null") rescue Exception end begin # Clean the pid file up. if File.exists?( File.(self.pid_file_dir + "/feed_updater.pid")) File.delete( File.(self.pid_file_dir + "/feed_updater.pid")) end rescue Exception end self.logger.prefix = "FeedUpdater".ljust(20) self.logger.level = 0 self.logger.info("Daemon stopped.") self.logger.level = self.[:log_level] @status = :stopped return nil if self.application.nil? begin self.application.stop() rescue Exception end return nil end |
#update_feeds ⇒ Object
Updates all of the feeds.
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 |
# File 'lib/feed_updater.rb', line 533 def update_feeds() self.logger.level = 0 self.logger.prefix = "FeedUpdater".ljust(20) ObjectSpace.garbage_collect() if defined?(@@on_begin) && @@on_begin != nil self.logger.info("Running custom startup event...") self.cloaker(&(@@on_begin)).bind(self).call() end if defined?(@feed_href_list_override) && @feed_href_list_override self.logger.info("Using custom feed list...") self.feed_href_list() else self.logger.info("Loading default feed list...") begin expire_time = (Time.now - 1.hour).utc expire_time_string = sprintf('%04d-%02d-%02d %02d:%02d:%02d', expire_time.year, expire_time.month, expire_time.day, expire_time.hour, expire_time.min, expire_time.sec) @feed_href_list = FeedTools.feed_cache.connection.execute( "SELECT href FROM cached_feeds WHERE " + "last_retrieved < '#{expire_time_string}'").to_a.flatten rescue Exception self.logger.warn("Default feed list failed, using fallback.") @feed_href_list = FeedTools.feed_cache.find(:all).collect do |feed| feed.href end self.logger.warn( "Fallback succeeded. Custom feed list override recommended.") end end self.logger.info("Updating #{@feed_href_list.size} feed(s)...") self.logger.level = self.[:log_level] @threads = [] @remaining_href_list = @feed_href_list.dup ObjectSpace.garbage_collect() begin_updating = false self.logger.info( "Starting up #{self.[:threads]} thread(s)...") mutex = Mutex.new for i in 0...self.[:threads] updater_thread = Thread.new do self.logger.level = self.[:log_level] self.logger.datetime_format = "%s" self.logger.progname = "FeedUpdater".ljust(20) while !Thread.current.respond_to?(:thread_id) && begin_updating == false Thread.pass end mutex.synchronize do self.logger.prefix = "Thread #{Thread.current.thread_id} ".ljust(20) self.logger.info("Thread started.") begin FeedTools.feed_cache.initialize_cache() if !FeedTools.feed_cache.set_up_correctly? self.logger.info("Problem with cache connection...") end rescue Exception => error self.logger.info(error) end end ObjectSpace.garbage_collect() Thread.pass while @remaining_href_list.size > 0 progress = nil mutex.synchronize do Thread.current.progress = self.progress_precentage() Thread.current.href = @remaining_href_list.shift() progress = sprintf("%.2f", Thread.current.progress) end begin begin Thread.current.feed = nil feed_load_benchmark = Benchmark.measure do Thread.current.feed = FeedTools::Feed.open(Thread.current.href) end Thread.pass if Thread.current.feed.live? unless @@on_update.nil? mutex.synchronize do progress = sprintf("%.2f", Thread.current.progress) self.logger.prefix = ("Thread #{Thread.current.thread_id} (#{progress}%)" ).ljust(20) self.cloaker(&(@@on_update)).bind(self).call( Thread.current.feed, feed_load_benchmark.real) end end else mutex.synchronize do progress = sprintf("%.2f", Thread.current.progress) self.logger.prefix = ("Thread #{Thread.current.thread_id} (#{progress}%)" ).ljust(20) self.logger.info( "'#{Thread.current.href}' unchanged " + "or unavailable, skipping.") end end rescue Exception => error mutex.synchronize do progress = sprintf("%.2f", Thread.current.progress) self.logger.prefix = ("Thread #{Thread.current.thread_id} (#{progress}%)" ).ljust(20) if @@on_error != nil self.cloaker(&(@@on_error)).bind(self).call( Thread.current.href, error) else self.logger.error( "Error updating '#{Thread.current.href}':") self.logger.error(error.class.name + ": " + error.) self.logger.error(error.class.backtrace) end end end rescue Exception => error mutex.synchronize do progress = sprintf("%.2f", Thread.current.progress) self.logger.prefix = ("Thread #{Thread.current.thread_id} " + "(#{progress}%)" ).ljust(20) self.logger.fatal("Critical unhandled error.") self.logger.fatal("Error updating '#{Thread.current.href}':") self.logger.fatal(error.class.name + ": " + error.) self.logger.fatal(error.class.backtrace) end end ObjectSpace.garbage_collect() Thread.pass end end @threads << updater_thread class <<updater_thread attr_accessor :thread_id attr_accessor :progress attr_accessor :href attr_accessor :feed end updater_thread.thread_id = i end mutex.synchronize do self.logger.prefix = "FeedUpdater".ljust(20) self.logger.info( "#{@threads.size} thread(s) successfully started...") begin_updating = true end Thread.pass ObjectSpace.garbage_collect() Thread.pass for i in 0...@threads.size mutex.synchronize do self.logger.prefix = "FeedUpdater".ljust(20) self.logger.info( "Joining on thread #{@threads[i].thread_id}...") end @threads[i].join end self.logger.prefix = "FeedUpdater".ljust(20) ObjectSpace.garbage_collect() self.logger.progname = nil unless @@on_complete.nil? self.cloaker(&(@@on_complete)).bind(self).call(@feed_href_list) end self.logger.level = 0 self.logger.info("Finished updating.") self.logger.level = self.[:log_level] end |
#updater_options ⇒ Object
Returns a hash of the currently set updater options.
249 250 251 252 253 254 255 256 257 258 259 |
# File 'lib/feed_updater.rb', line 249 def () if !defined?(@updater_options) || @updater_options.nil? @updater_options = { :start_delay => true, :threads => 1, :sleep_time => 60, :log_level => 0 } end return @updater_options end |