insrc-whenever 0.4.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,161 @@
1
+ module Whenever
2
+ class JobList
3
+
4
+ def initialize(options)
5
+ @jobs = Hash.new
6
+ @env = Hash.new
7
+
8
+ case options
9
+ when String
10
+ config = options
11
+ when Hash
12
+ config = if options[:string]
13
+ options[:string]
14
+ elsif options[:file]
15
+ File.read(options[:file])
16
+ end
17
+ pre_set(options[:set])
18
+ end
19
+
20
+ eval(config)
21
+ end
22
+
23
+ def set(variable, value)
24
+ return if instance_variable_defined?("@#{variable}".to_sym)
25
+
26
+ instance_variable_set("@#{variable}".to_sym, value)
27
+ self.class.send(:attr_reader, variable.to_sym)
28
+ end
29
+
30
+ def env(variable, value)
31
+ @env[variable.to_s] = value
32
+ end
33
+
34
+ def every(frequency, options = {})
35
+ @current_time_scope = frequency
36
+ @options = options
37
+ yield
38
+ end
39
+
40
+ def command(task, options = {})
41
+ # :cron_log was an old option for output redirection, it remains for backwards compatibility
42
+ options[:output] = (options[:cron_log] || @cron_log) if defined?(@cron_log) || options.has_key?(:cron_log)
43
+ # :output is the newer, more flexible option.
44
+ options[:output] = @output if defined?(@output) && !options.has_key?(:output)
45
+ options[:class] ||= Whenever::Job::Default
46
+ @jobs[@current_time_scope] ||= []
47
+ @jobs[@current_time_scope] << options[:class].new(@options.merge(:task => task).merge(options))
48
+ end
49
+
50
+ def runner(task, options = {})
51
+ options.reverse_merge!(:environment => @environment, :path => @path)
52
+ options[:class] = Whenever::Job::Runner
53
+ command(task, options)
54
+ end
55
+
56
+ def rake(task, options = {})
57
+ options.reverse_merge!(:environment => @environment, :path => @path)
58
+ options[:class] = Whenever::Job::RakeTask
59
+ command(task, options)
60
+ end
61
+
62
+ def generate_cron_output
63
+ set_path_environment_variable
64
+
65
+ [environment_variables, cron_jobs].compact.join
66
+ end
67
+
68
+ private
69
+
70
+ #
71
+ # Takes a string like: "variable1=something&variable2=somethingelse"
72
+ # and breaks it into variable/value pairs. Used for setting variables at runtime from the command line.
73
+ # Only works for setting values as strings.
74
+ #
75
+ def pre_set(variable_string = nil)
76
+ return if variable_string.blank?
77
+
78
+ pairs = variable_string.split('&')
79
+ pairs.each do |pair|
80
+ next unless pair.index('=')
81
+ variable, value = *pair.split('=')
82
+ set(variable.strip, value.strip) unless variable.blank? || value.blank?
83
+ end
84
+ end
85
+
86
+ def set_path_environment_variable
87
+ return if path_should_not_be_set_automatically?
88
+ @env[:PATH] = read_path unless read_path.blank?
89
+ end
90
+
91
+ def read_path
92
+ ENV['PATH'] if ENV
93
+ end
94
+
95
+ def path_should_not_be_set_automatically?
96
+ @set_path_automatically === false || @env[:PATH] || @env["PATH"]
97
+ end
98
+
99
+ def environment_variables
100
+ return if @env.empty?
101
+
102
+ output = []
103
+ @env.each do |key, val|
104
+ output << "#{key}=#{val}\n"
105
+ end
106
+ output << "\n"
107
+
108
+ output.join
109
+ end
110
+
111
+ #
112
+ # Takes the standard cron output that Whenever generates and finds
113
+ # similar entries that can be combined. For example: If a job should run
114
+ # at 3:02am and 4:02am, instead of creating two jobs this method combines
115
+ # them into one that runs on the 2nd minute at the 3rd and 4th hour.
116
+ #
117
+ def combine(entries)
118
+ entries.map! { |entry| entry.split(/ +/, 6) }
119
+ 0.upto(4) do |f|
120
+ (entries.length-1).downto(1) do |i|
121
+ next if entries[i][f] == '*'
122
+ comparison = entries[i][0...f] + entries[i][f+1..-1]
123
+ (i-1).downto(0) do |j|
124
+ next if entries[j][f] == '*'
125
+ if comparison == entries[j][0...f] + entries[j][f+1..-1]
126
+ entries[j][f] += ',' + entries[i][f]
127
+ entries.delete_at(i)
128
+ break
129
+ end
130
+ end
131
+ end
132
+ end
133
+
134
+ entries.map { |entry| entry.join(' ') }
135
+ end
136
+
137
+ def cron_jobs
138
+ return if @jobs.empty?
139
+
140
+ shortcut_jobs = []
141
+ regular_jobs = []
142
+
143
+ @jobs.each do |time, jobs|
144
+ jobs.each do |job|
145
+ Whenever::Output::Cron.output(time, job) do |cron|
146
+ cron << "\n\n"
147
+
148
+ if cron.starts_with?("@")
149
+ shortcut_jobs << cron
150
+ else
151
+ regular_jobs << cron
152
+ end
153
+ end
154
+ end
155
+ end
156
+
157
+ shortcut_jobs.join + combine(regular_jobs).join
158
+ end
159
+
160
+ end
161
+ end
@@ -0,0 +1,27 @@
1
+ module Whenever
2
+ module Job
3
+ class Default
4
+
5
+ attr_accessor :task, :at, :output, :output_redirection
6
+
7
+ def initialize(options = {})
8
+ @task = options[:task]
9
+ @at = options[:at]
10
+ @output_redirection = options.has_key?(:output) ? options[:output] : :not_set
11
+ @environment = options[:environment] || :production
12
+ @path = options[:path] || Whenever.path
13
+ end
14
+
15
+ def output
16
+ task
17
+ end
18
+
19
+ protected
20
+
21
+ def path_required
22
+ raise ArgumentError, "No path available; set :path, '/your/path' in your schedule file" if @path.blank?
23
+ end
24
+
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,12 @@
1
+ module Whenever
2
+ module Job
3
+ class RakeTask < Whenever::Job::Default
4
+
5
+ def output
6
+ path_required
7
+ "cd #{@path} && RAILS_ENV=#{@environment} /usr/bin/env rake #{task}"
8
+ end
9
+
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,12 @@
1
+ module Whenever
2
+ module Job
3
+ class Runner < Whenever::Job::Default
4
+
5
+ def output
6
+ path_required
7
+ %Q(#{File.join(@path, 'script', 'runner')} -e #{@environment} #{task.inspect})
8
+ end
9
+
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,139 @@
1
+ module Whenever
2
+ module Output
3
+
4
+ class Cron
5
+
6
+ attr_accessor :time, :task
7
+
8
+ def initialize(time = nil, task = nil, at = nil, output_redirection = nil)
9
+ @time = time
10
+ @task = task
11
+ @at = at.is_a?(String) ? (Chronic.parse(at) || 0) : (at || 0)
12
+ @output_redirection = output_redirection
13
+ end
14
+
15
+ def self.enumerate(item)
16
+ if item and item.is_a?(String)
17
+ items = item.split(',')
18
+ else
19
+ items = item
20
+ items = [items] unless items and items.respond_to?(:each)
21
+ end
22
+ items
23
+ end
24
+
25
+ def self.output(times, job)
26
+ enumerate(times).each do |time|
27
+ enumerate(job.at).each do |at|
28
+ yield new(time, job.output, at, job.output_redirection).output
29
+ end
30
+ end
31
+ end
32
+
33
+ def output
34
+ [time_in_cron_syntax, task, output_redirection].compact.join(' ').strip
35
+ end
36
+
37
+ def time_in_cron_syntax
38
+ case @time
39
+ when Symbol then parse_symbol
40
+ when String then parse_as_string
41
+ else parse_time
42
+ end
43
+ end
44
+
45
+ def output_redirection
46
+ OutputRedirection.new(@output_redirection).to_s unless @output_redirection == :not_set
47
+ end
48
+
49
+ protected
50
+
51
+ def parse_symbol
52
+ shortcut = case @time
53
+ when :reboot then '@reboot'
54
+ when :year, :yearly then '@annually'
55
+ when :day, :daily then '@daily'
56
+ when :midnight then '@midnight'
57
+ when :month, :monthly then '@monthly'
58
+ when :week, :weekly then '@weekly'
59
+ when :hour, :hourly then '@hourly'
60
+ end
61
+
62
+ if shortcut
63
+ if @at > 0
64
+ raise ArgumentError, "You cannot specify an ':at' when using the shortcuts for times."
65
+ else
66
+ return shortcut
67
+ end
68
+ else
69
+ parse_as_string
70
+ end
71
+ end
72
+
73
+ def parse_time
74
+ timing = Array.new(5, '*')
75
+ case @time
76
+ when 0.seconds...1.minute
77
+ raise ArgumentError, "Time must be in minutes or higher"
78
+ when 1.minute...1.hour
79
+ minute_frequency = @time / 60
80
+ timing[0] = comma_separated_timing(minute_frequency, 59)
81
+ when 1.hour...1.day
82
+ hour_frequency = (@time / 60 / 60).round
83
+ timing[0] = @at.is_a?(Time) ? @at.min : @at
84
+ timing[1] = comma_separated_timing(hour_frequency, 23)
85
+ when 1.day...1.month
86
+ day_frequency = (@time / 24 / 60 / 60).round
87
+ timing[0] = @at.is_a?(Time) ? @at.min : 0
88
+ timing[1] = @at.is_a?(Time) ? @at.hour : @at
89
+ timing[2] = comma_separated_timing(day_frequency, 31, 1)
90
+ when 1.month..12.months
91
+ month_frequency = (@time / 30 / 24 / 60 / 60).round
92
+ timing[0] = @at.is_a?(Time) ? @at.min : 0
93
+ timing[1] = @at.is_a?(Time) ? @at.hour : 0
94
+ timing[2] = @at.is_a?(Time) ? @at.day : (@at.zero? ? 1 : @at)
95
+ timing[3] = comma_separated_timing(month_frequency, 12, 1)
96
+ else
97
+ return parse_as_string
98
+ end
99
+ timing.join(' ')
100
+ end
101
+
102
+ def parse_as_string
103
+ return unless @time
104
+ string = @time.to_s
105
+
106
+ timing = Array.new(4, '*')
107
+ timing[0] = @at.is_a?(Time) ? @at.min : 0
108
+ timing[1] = @at.is_a?(Time) ? @at.hour : 0
109
+
110
+ return (timing << '1-5') * " " if string.downcase.index('weekday')
111
+ return (timing << '6,0') * " " if string.downcase.index('weekend')
112
+
113
+ %w(sun mon tue wed thu fri sat).each_with_index do |day, i|
114
+ return (timing << i) * " " if string.downcase.index(day)
115
+ end
116
+
117
+ raise ArgumentError, "Couldn't parse: #{@time}"
118
+ end
119
+
120
+ def comma_separated_timing(frequency, max, start = 0)
121
+ return start if frequency.blank? || frequency.zero?
122
+ return '*' if frequency == 1
123
+ return frequency if frequency > (max * 0.5).ceil
124
+
125
+ original_start = start
126
+
127
+ start += frequency unless (max + 1).modulo(frequency).zero? || start > 0
128
+ output = (start..max).step(frequency).to_a
129
+
130
+ max_occurances = (max.to_f / (frequency.to_f)).round
131
+ max_occurances += 1 if original_start.zero?
132
+
133
+ output[0, max_occurances].join(',')
134
+ end
135
+
136
+ end
137
+
138
+ end
139
+ end
@@ -0,0 +1,54 @@
1
+ module Whenever
2
+ module Output
3
+ class Cron
4
+ class OutputRedirection
5
+
6
+ def initialize(output)
7
+ @output = output
8
+ end
9
+
10
+ def to_s
11
+ return '' unless defined?(@output)
12
+ case @output
13
+ when String then redirect_from_string
14
+ when Hash then redirect_from_hash
15
+ when NilClass then ">> /dev/null 2>&1"
16
+ else ''
17
+ end
18
+ end
19
+
20
+ protected
21
+
22
+ def stdout
23
+ return unless @output.has_key?(:standard)
24
+ @output[:standard].nil? ? '/dev/null' : @output[:standard]
25
+ end
26
+
27
+ def stderr
28
+ return unless @output.has_key?(:error)
29
+ @output[:error].nil? ? '/dev/null' : @output[:error]
30
+ end
31
+
32
+ def redirect_from_hash
33
+ case
34
+ when stdout == '/dev/null' && stderr == '/dev/null'
35
+ ">> /dev/null 2>&1"
36
+ when stdout && stderr
37
+ ">> #{stdout} 2> #{stderr}"
38
+ when stderr
39
+ "2> #{stderr}"
40
+ when stdout
41
+ ">> #{stdout}"
42
+ else
43
+ ''
44
+ end
45
+ end
46
+
47
+ def redirect_from_string
48
+ ">> #{@output} 2>&1"
49
+ end
50
+
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,3 @@
1
+ module Whenever
2
+ VERSION = '0.4.0'
3
+ end unless defined?(Whenever::VERSION)
@@ -0,0 +1,101 @@
1
+ require File.expand_path(File.dirname(__FILE__) + "/test_helper")
2
+
3
+ class CommandLineTest < Test::Unit::TestCase
4
+
5
+ context "A command line write" do
6
+ setup do
7
+ File.expects(:exists?).with('config/schedule.rb').returns(true)
8
+ @command = Whenever::CommandLine.new(:write => true, :identifier => 'My identifier')
9
+ @task = "#{two_hours} /my/command"
10
+ Whenever.expects(:cron).returns(@task)
11
+ end
12
+
13
+ should "output the cron job with identifier blocks" do
14
+ output = <<-EXPECTED
15
+ # Begin Whenever generated tasks for: My identifier
16
+ #{@task}
17
+ # End Whenever generated tasks for: My identifier
18
+ EXPECTED
19
+
20
+ assert_equal output, @command.send(:whenever_cron)
21
+ end
22
+
23
+ should "write the crontab when run" do
24
+ @command.expects(:write_crontab).returns(true)
25
+ assert @command.run
26
+ end
27
+ end
28
+
29
+ context "A command line update" do
30
+ setup do
31
+ File.expects(:exists?).with('config/schedule.rb').returns(true)
32
+ @command = Whenever::CommandLine.new(:update => true, :identifier => 'My identifier')
33
+ @task = "#{two_hours} /my/command"
34
+ Whenever.expects(:cron).returns(@task)
35
+ end
36
+
37
+ should "add the cron to the end of the file if there is no existing identifier block" do
38
+ existing = '# Existing crontab'
39
+ @command.expects(:read_crontab).at_least_once.returns(existing)
40
+
41
+ new_cron = <<-EXPECTED
42
+ #{existing}
43
+
44
+ # Begin Whenever generated tasks for: My identifier
45
+ #{@task}
46
+ # End Whenever generated tasks for: My identifier
47
+ EXPECTED
48
+
49
+ assert_equal new_cron, @command.send(:updated_crontab)
50
+
51
+ @command.expects(:write_crontab).with(new_cron).returns(true)
52
+ assert @command.run
53
+ end
54
+
55
+ should "replace an existing block if the identifier matches" do
56
+ existing = <<-EXISTING_CRON
57
+ # Something
58
+
59
+ # Begin Whenever generated tasks for: My identifier
60
+ My whenever job that was already here
61
+ # End Whenever generated tasks for: My identifier
62
+
63
+ # Begin Whenever generated tasks for: Other identifier
64
+ This shouldn't get replaced
65
+ # End Whenever generated tasks for: Other identifier
66
+ EXISTING_CRON
67
+
68
+ @command.expects(:read_crontab).at_least_once.returns(existing)
69
+
70
+ new_cron = <<-NEW_CRON
71
+ # Something
72
+
73
+ # Begin Whenever generated tasks for: My identifier
74
+ #{@task}
75
+ # End Whenever generated tasks for: My identifier
76
+
77
+ # Begin Whenever generated tasks for: Other identifier
78
+ This shouldn't get replaced
79
+ # End Whenever generated tasks for: Other identifier
80
+ NEW_CRON
81
+
82
+ assert_equal new_cron, @command.send(:updated_crontab)
83
+
84
+ @command.expects(:write_crontab).with(new_cron).returns(true)
85
+ assert @command.run
86
+ end
87
+ end
88
+
89
+ context "A command line update with no identifier" do
90
+ setup do
91
+ File.expects(:exists?).with('config/schedule.rb').returns(true)
92
+ Whenever::CommandLine.any_instance.expects(:default_identifier).returns('DEFAULT')
93
+ @command = Whenever::CommandLine.new(:update => true, :file => @file)
94
+ end
95
+
96
+ should "use the default identifier" do
97
+ assert_equal "Whenever generated tasks for: DEFAULT", @command.send(:comment_base)
98
+ end
99
+ end
100
+
101
+ end