ruby_raider 4.0.1 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/e2e_tests.yml +3 -0
  3. data/README.md +58 -1
  4. data/RELEASE.md +25 -0
  5. data/lib/commands/schedule_commands.rb +84 -0
  6. data/lib/generators/templates/common/git_ignore.tt +1 -0
  7. data/lib/ruby_raider/runtime/retry_reset.rb +32 -0
  8. data/lib/ruby_raider/runtime/rspec.rb +1 -0
  9. data/lib/ruby_raider/runtime/show_browser.rb +53 -0
  10. data/lib/ruby_raider/runtime.rb +2 -0
  11. data/lib/ruby_raider.rb +31 -0
  12. data/lib/utilities/schedules/adapter.rb +22 -0
  13. data/lib/utilities/schedules/base.rb +27 -0
  14. data/lib/utilities/schedules/kind.rb +74 -0
  15. data/lib/utilities/schedules/legacy.rb +196 -0
  16. data/lib/utilities/schedules/legacy_stub.rb +62 -0
  17. data/lib/utilities/schedules/next_run.rb +61 -0
  18. data/lib/utilities/schedules/notifier.rb +76 -0
  19. data/lib/utilities/schedules/os/command_runner.rb +73 -0
  20. data/lib/utilities/schedules/os/cron.rb +147 -0
  21. data/lib/utilities/schedules/os/launchd.rb +182 -0
  22. data/lib/utilities/schedules/os/linux.rb +81 -0
  23. data/lib/utilities/schedules/os/systemd.rb +194 -0
  24. data/lib/utilities/schedules/os/task_scheduler.rb +195 -0
  25. data/lib/utilities/schedules/os_enumerator.rb +30 -0
  26. data/lib/utilities/schedules/project.rb +70 -0
  27. data/lib/utilities/schedules/rule.rb +162 -0
  28. data/lib/utilities/schedules/run_lock.rb +160 -0
  29. data/lib/utilities/schedules/run_log.rb +122 -0
  30. data/lib/utilities/schedules/run_report.rb +139 -0
  31. data/lib/utilities/schedules/run_wrapper.rb +216 -0
  32. data/lib/utilities/schedules/schedule.rb +89 -0
  33. data/lib/utilities/schedules/schedule_store.rb +53 -0
  34. data/lib/utilities/schedules/scheduler.rb +178 -0
  35. data/lib/utilities/schedules/scheduler_steps.rb +69 -0
  36. data/lib/utilities/schedules/selection.rb +133 -0
  37. data/lib/utilities/schedules/spawn.rb +68 -0
  38. data/lib/utilities/schedules/store.rb +139 -0
  39. data/lib/version +1 -1
  40. data/ruby_raider.gemspec +1 -0
  41. data/sig/commands/schedule_commands.rbs +12 -0
  42. data/sig/ruby_raider/runtime/retry_reset.rbs +7 -0
  43. data/sig/ruby_raider/runtime/show_browser.rbs +27 -0
  44. data/sig/ruby_raider.rbs +6 -0
  45. data/sig/utilities/schedules/adapter.rbs +5 -0
  46. data/sig/utilities/schedules/base.rbs +15 -0
  47. data/sig/utilities/schedules/kind.rbs +32 -0
  48. data/sig/utilities/schedules/legacy.rbs +45 -0
  49. data/sig/utilities/schedules/legacy_stub.rbs +15 -0
  50. data/sig/utilities/schedules/next_run.rbs +15 -0
  51. data/sig/utilities/schedules/notifier.rbs +29 -0
  52. data/sig/utilities/schedules/os/command_runner.rbs +27 -0
  53. data/sig/utilities/schedules/os/cron.rbs +34 -0
  54. data/sig/utilities/schedules/os/launchd.rbs +46 -0
  55. data/sig/utilities/schedules/os/linux.rbs +33 -0
  56. data/sig/utilities/schedules/os/systemd.rbs +44 -0
  57. data/sig/utilities/schedules/os/task_scheduler.rbs +56 -0
  58. data/sig/utilities/schedules/os_enumerator.rbs +12 -0
  59. data/sig/utilities/schedules/project.rbs +22 -0
  60. data/sig/utilities/schedules/rule.rbs +72 -0
  61. data/sig/utilities/schedules/run_lock.rbs +29 -0
  62. data/sig/utilities/schedules/run_log.rbs +33 -0
  63. data/sig/utilities/schedules/run_report.rbs +34 -0
  64. data/sig/utilities/schedules/run_wrapper.rbs +45 -0
  65. data/sig/utilities/schedules/schedule.rbs +27 -0
  66. data/sig/utilities/schedules/schedule_store.rbs +21 -0
  67. data/sig/utilities/schedules/scheduler.rbs +49 -0
  68. data/sig/utilities/schedules/scheduler_steps.rbs +22 -0
  69. data/sig/utilities/schedules/selection.rbs +36 -0
  70. data/sig/utilities/schedules/spawn.rbs +10 -0
  71. data/sig/utilities/schedules/store.rbs +39 -0
  72. data/spec/commands/schedule_commands_spec.rb +284 -0
  73. data/spec/integration/content/common_content_spec.rb +8 -2
  74. data/spec/integration/content/gemfile_content_spec.rb +2 -2
  75. data/spec/runtime/retry_reset_spec.rb +112 -0
  76. data/spec/runtime/show_browser_project_spec.rb +70 -0
  77. data/spec/runtime/show_browser_spec.rb +101 -0
  78. data/spec/utilities/schedules/kind_spec.rb +81 -0
  79. data/spec/utilities/schedules/legacy_spec.rb +433 -0
  80. data/spec/utilities/schedules/legacy_stub_spec.rb +144 -0
  81. data/spec/utilities/schedules/next_run_spec.rb +119 -0
  82. data/spec/utilities/schedules/notifier_spec.rb +120 -0
  83. data/spec/utilities/schedules/os/command_runner_spec.rb +55 -0
  84. data/spec/utilities/schedules/os/cron_spec.rb +292 -0
  85. data/spec/utilities/schedules/os/launchd_spec.rb +306 -0
  86. data/spec/utilities/schedules/os/linux_spec.rb +163 -0
  87. data/spec/utilities/schedules/os/list_ids_spec.rb +202 -0
  88. data/spec/utilities/schedules/os/systemd_spec.rb +333 -0
  89. data/spec/utilities/schedules/os/task_scheduler_spec.rb +511 -0
  90. data/spec/utilities/schedules/os_entry_spec.rb +54 -0
  91. data/spec/utilities/schedules/os_enumerator_spec.rb +57 -0
  92. data/spec/utilities/schedules/project_spec.rb +125 -0
  93. data/spec/utilities/schedules/run_lock_spec.rb +143 -0
  94. data/spec/utilities/schedules/run_log_spec.rb +83 -0
  95. data/spec/utilities/schedules/run_report_spec.rb +150 -0
  96. data/spec/utilities/schedules/run_wrapper_integration_spec.rb +166 -0
  97. data/spec/utilities/schedules/run_wrapper_spec.rb +430 -0
  98. data/spec/utilities/schedules/schedule_spec.rb +120 -0
  99. data/spec/utilities/schedules/schedule_store_spec.rb +151 -0
  100. data/spec/utilities/schedules/scheduler_launchd_spec.rb +77 -0
  101. data/spec/utilities/schedules/scheduler_spec.rb +445 -0
  102. data/spec/utilities/schedules/selection_spec.rb +176 -0
  103. data/spec/utilities/schedules/spawn_spec.rb +104 -0
  104. metadata +106 -2
@@ -0,0 +1,196 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'yaml'
4
+ require_relative 'adapter'
5
+ require_relative 'os_enumerator'
6
+ require_relative 'rule'
7
+
8
+ module RubyRaider
9
+ module Schedules
10
+ # Removes the schedules Ruby Raider 4.1 made in a project (Kind::FLOW_LEGACY): they can't run in 4.2.
11
+ # Every `raider schedule` command runs it first, and so does the hidden stub an old OS entry reaches.
12
+ # It only ever acts on this project's os_ids, each recomputed from the project's real path and a name
13
+ # (from the old schedules.yml or the OS scheduler); an os_id stored in the yml is never used. It deletes
14
+ # the old schedules.yml once every entry is gone, and nothing else, and only when the file is a 4.1
15
+ # schedules file all of whose entries are this project's: a file it can't read, or one with an entry
16
+ # of another path (a moved project), stays, since its os_ids are what the user needs to remove by hand.
17
+ # An adapter's error text is passed through as is on purpose: it names the os_id the README says to look for.
18
+ # Never raises.
19
+ # :reek:TooManyConstants { max_constants: 6 } -- the kind, file, size cap, open flags and the old rule
20
+ # :reek:TooManyInstanceVariables { max_instance_variables: 5 } -- the project, its root, adapter, stream and whether the yml may go
21
+ class Legacy
22
+ KIND = Kind::FLOW_LEGACY
23
+ FILE = 'schedules.yml'
24
+ MAX_BYTES = 1_000_000
25
+ NOFOLLOW = defined?(File::NOFOLLOW) ? File::NOFOLLOW : 0
26
+ NONBLOCK = defined?(File::NONBLOCK) ? File::NONBLOCK : 0
27
+
28
+ # The 4.1 rule, for its os_ids only (os_id_for, os_id_prefix_for)
29
+ class OldRule < Rule
30
+ def self.kind = KIND
31
+ end
32
+
33
+ # project: a Project (its real root); adapter: nil picks this machine's OS scheduler when first needed
34
+ def initialize(project, adapter: nil, err: $stderr)
35
+ @project = project
36
+ @root = project.root
37
+ @adapter = adapter
38
+ @err = err
39
+ @yml_clean = false
40
+ end
41
+
42
+ # True when the project has a real .raider/flows folder (4.1 always made one; this never deletes it):
43
+ # without one there is nothing to clean, so `raider schedule` skips the cleanup for one lstat
44
+ def self.folder?(project)
45
+ File.lstat(File.join(project.root, KIND.dir)).directory?
46
+ rescue SystemCallError
47
+ false
48
+ end
49
+
50
+ # Removes every 4.1 schedule of the project, then its schedules.yml. Prints and returns the notice, nil
51
+ # when there was nothing to remove. last: the name of the entry running this (the stub's own), removed
52
+ # after the notice is written and the yml deleted, since removing it may end this process.
53
+ def cleanup(last: nil)
54
+ current = adapter
55
+ return nil unless current
56
+
57
+ names = (yml_names | OsEnumerator.new(current, schedule_class: OldRule, root: @root).names).sort
58
+ own = names.delete(last) if last
59
+ removed, failed = remove_all(current, names)
60
+ removed << own if own
61
+ delete_yml if failed.empty?
62
+ notice = notice(removed, failed)
63
+ say(notice) if notice
64
+ remove_own(current, own) if own
65
+ notice
66
+ rescue StandardError => e
67
+ say("Could not remove the schedules made with Ruby Raider 4.1: #{e.message}")
68
+ end
69
+
70
+ private
71
+
72
+ def adapter
73
+ @adapter ||= Schedules.adapter(kind: KIND)
74
+ rescue Error
75
+ nil
76
+ end
77
+
78
+ # [removed names, [name, message] of each that failed]; one already gone is neither
79
+ def remove_all(current, names)
80
+ removed = []
81
+ failed = []
82
+ names.each do |name|
83
+ removed << name if current.remove(OldRule.os_id_for(@root, name))
84
+ rescue Error, SystemCallError => e
85
+ failed << [name, e.message]
86
+ end
87
+ [removed, failed]
88
+ end
89
+
90
+ # Its own entry last: the notice is out (and flushed) and the yml gone before this may end the process
91
+ def remove_own(current, name)
92
+ current.remove(OldRule.os_id_for(@root, name))
93
+ rescue Error, SystemCallError => e
94
+ say("Could not remove #{name}: #{e.message}")
95
+ end
96
+
97
+ def notice(removed, failed)
98
+ lines = []
99
+ lines << removed_text(removed) unless removed.empty?
100
+ lines << failed_text(failed) unless failed.empty?
101
+ lines.empty? ? nil : Schedules.printable(lines.join(' '))
102
+ end
103
+
104
+ def removed_text(names)
105
+ one = names.size == 1
106
+ "Removed #{counted(names.size)} made with Ruby Raider 4.1 (#{names.join(', ')}); #{one ? 'it' : 'they'} can't run in 4.2. " \
107
+ "Add #{one ? 'it' : 'them'} again with raider schedule add."
108
+ end
109
+
110
+ def failed_text(failed)
111
+ reasons = failed.map { |name, message| "#{name}: #{message}" }.join(', ')
112
+ "Could not remove #{counted(failed.size)} made with Ruby Raider 4.1 (#{reasons}); " \
113
+ "#{failed.size == 1 ? 'it is' : 'they are'} tried again next time."
114
+ end
115
+
116
+ def counted(count) = count == 1 ? '1 schedule' : "#{count} schedules"
117
+
118
+ # One printable line on err, flushed; returns it
119
+ def say(text)
120
+ line = Schedules.printable(text)
121
+ err = @err
122
+ err.puts(line)
123
+ err.flush if err.respond_to?(:flush)
124
+ line
125
+ rescue StandardError
126
+ line
127
+ end
128
+
129
+ def dir = File.join(@root, KIND.dir)
130
+
131
+ def yml = File.join(dir, FILE)
132
+
133
+ # .raider and .raider/flows are real folders, not links (a missing one is one failed lstat)
134
+ def real_dirs? = [File.join(@root, '.raider'), dir].all? { |path| File.lstat(path).directory? }
135
+
136
+ # The names of the yml's entries that 4.1 would read as this project's: valid, with the os_id it
137
+ # computes for this project; anything else in the file, or a file that is not a schedules file, gives
138
+ # none. The yml may go only when it was a schedules file and every entry was one of these.
139
+ def yml_names
140
+ entries = read_entries
141
+ return [] unless entries
142
+
143
+ names = entries.map { |entry| entry_name(entry) }
144
+ @yml_clean = names.all?
145
+ names.compact.uniq
146
+ end
147
+
148
+ def entry_name(entry)
149
+ return nil unless entry.is_a?(Hash)
150
+
151
+ name = entry['name']
152
+ name if name.is_a?(String) && KIND.valid_name?(name) && entry['os_id'] == OldRule.os_id_for(@root, name)
153
+ end
154
+
155
+ # The entries of a schedules file ([] for an empty document); nil when there is none or it is not one
156
+ def read_entries
157
+ text = read_text
158
+ return nil unless text
159
+
160
+ data = YAML.safe_load(text)
161
+ return [] unless data
162
+
163
+ entries = data.is_a?(Hash) ? data['schedules'] : nil
164
+ entries.is_a?(Array) ? entries : nil
165
+ rescue Psych::Exception
166
+ nil
167
+ end
168
+
169
+ # The yml through one handle that is not a link, a regular file up to MAX_BYTES; nil otherwise.
170
+ # The folders are lstat'ed and then the file opened (and later unlinked) by path, so a folder swapped
171
+ # for a link in between is followed: that takes write access to the project, and Ruby has no
172
+ # openat/unlinkat to close the window.
173
+ def read_text
174
+ return nil unless real_dirs?
175
+
176
+ File.open(yml, File::RDONLY | NONBLOCK | NOFOLLOW) do |file|
177
+ next nil unless file.stat.file?
178
+
179
+ text = file.read(MAX_BYTES + 1) || +'' # an empty file reads nil
180
+ text.bytesize > MAX_BYTES ? nil : text.force_encoding(Encoding::UTF_8)
181
+ end
182
+ rescue SystemCallError
183
+ nil
184
+ end
185
+
186
+ # The yml only, when it was read as a clean schedules file and the folders and it still are real
187
+ # (a link or folder stays)
188
+ def delete_yml
189
+ path = yml
190
+ File.unlink(path) if @yml_clean && real_dirs? && File.lstat(path).file?
191
+ rescue SystemCallError
192
+ nil
193
+ end
194
+ end
195
+ end
196
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'legacy'
4
+ require_relative 'project'
5
+
6
+ module RubyRaider
7
+ module Schedules
8
+ # What a Ruby Raider 4.1 OS entry reaches now: `raider flow run NAME --project ROOT --trigger schedule ...`.
9
+ # Raider.start sends it here before Thor, so any argv works. It removes the project's 4.1 schedules (its
10
+ # own entry last), writes one line to stderr (the entry's scheduler.log) and always exits 2. It never
11
+ # sends a notification and never takes the project from the current folder.
12
+ module LegacyStub
13
+ EXIT = 2
14
+ REMOVED = 'This command was removed in Ruby Raider 4.2. To run tests on a schedule, use raider schedule add.'
15
+ OPTION = '--project'
16
+
17
+ # The exit code: always 2
18
+ def self.run(argv, err: $stderr)
19
+ root = project_root(argv)
20
+ root ? clean(root, own_name(argv), err) : err.puts(REMOVED)
21
+ EXIT
22
+ rescue StandardError
23
+ EXIT
24
+ end
25
+
26
+ def self.clean(root, name, err)
27
+ return if Legacy.new(Project.new(root), err: err).cleanup(last: name)
28
+
29
+ err.puts(Schedules.printable("This schedule was made with Ruby Raider 4.1 and can't run in 4.2, and none was found for #{root} " \
30
+ 'to remove: see Upgrading from 4.1 in the README.'))
31
+ end
32
+
33
+ # The real path of the first --project value: valid UTF-8, absolute, a folder with a regular Gemfile
34
+ def self.project_root(argv)
35
+ path = project_value(argv)
36
+ return nil unless path.is_a?(String) && path.valid_encoding? && !path.include?("\0") && File.absolute_path?(path)
37
+
38
+ root = File.realpath(path)
39
+ File.directory?(root) && File.lstat(File.join(root, 'Gemfile')).file? ? root : nil
40
+ rescue SystemCallError
41
+ nil
42
+ end
43
+
44
+ # --project VALUE or --project=VALUE, whichever comes first
45
+ def self.project_value(argv)
46
+ argv.each_with_index do |arg, index|
47
+ next unless arg.is_a?(String) && arg.valid_encoding?
48
+ return argv[index + 1] if arg == OPTION
49
+ return arg.delete_prefix("#{OPTION}=") if arg.start_with?("#{OPTION}=")
50
+ end
51
+ nil
52
+ end
53
+
54
+ # The name after the first run, when it is a valid 4.1 name
55
+ def self.own_name(argv)
56
+ index = argv.index('run')
57
+ name = index && argv[index + 1]
58
+ name if name.is_a?(String) && name.valid_encoding? && Legacy::KIND.valid_name?(name)
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'date'
4
+ require_relative 'base'
5
+
6
+ module RubyRaider
7
+ module Schedules
8
+ # When a schedule next runs, in local time, as launchd, schtasks, systemd and cron count it.
9
+ # A day, weekday or week rule whose time falls in a spring-forward gap runs at the first minute
10
+ # after the gap; one that falls in a fall-back hour runs at its first occurrence only.
11
+ # An hour rule runs at every real instant whose local minute matches, so twice in a fall-back hour.
12
+ module NextRun
13
+ WDAYS = %w[sun mon tue wed thu fri sat].freeze
14
+ # The longest stretch to search: a week rule, plus a day of slack
15
+ SEARCH_DAYS = 8
16
+ # The minutes to search for an hour rule: an hour, plus an hour of offset change
17
+ SEARCH_MINUTES = 120
18
+
19
+ module_function
20
+
21
+ def after(schedule, now)
22
+ local_now = now.getlocal
23
+ schedule.every == 'hour' ? next_minute(schedule.minute, local_now) : next_day(schedule, local_now)
24
+ end
25
+
26
+ def next_minute(minute, now)
27
+ time = Time.at(now.to_i - now.sec + 60).localtime
28
+ SEARCH_MINUTES.times do
29
+ return time if time.min == minute
30
+
31
+ time += 60
32
+ end
33
+ raise Error, "No local time with minute #{minute} after #{now}"
34
+ end
35
+
36
+ def next_day(schedule, now)
37
+ today = Date.new(now.year, now.month, now.day)
38
+ (0..SEARCH_DAYS).each do |offset|
39
+ date = today + offset
40
+ next unless schedule.days.include?(WDAYS[date.wday])
41
+
42
+ time = local(date, schedule.hour, schedule.minute)
43
+ return time if time > now
44
+ end
45
+ raise Error, "No run for #{schedule.rule_text} after #{now}"
46
+ end
47
+
48
+ # The first instant whose local wall clock reaches date hour:minute
49
+ def local(date, hour, minute)
50
+ wanted = [date.year, date.month, date.day, hour, minute]
51
+ time = Time.local(*wanted)
52
+ time += 60 while (wall(time) <=> wanted).negative?
53
+ time -= 60 until (wall(time - 60) <=> wanted).negative?
54
+ earlier = time - 3600
55
+ wall(earlier) == wanted ? earlier : time
56
+ end
57
+
58
+ def wall(time) = [time.year, time.month, time.day, time.hour, time.min]
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rbconfig'
4
+ require_relative 'base'
5
+ require_relative 'os/command_runner'
6
+
7
+ module RubyRaider
8
+ module Schedules
9
+ # A desktop notification for a scheduled run with --notify. The title and message only ever travel as argv
10
+ # items after `--` (osascript, notify-send: so a title like -e is not read as an option or a script) or as
11
+ # environment values (PowerShell), so a hostile schedule name or test title can't run as AppleScript or PowerShell. Never raises: a notification
12
+ # that can't be shown must not change how the run ends.
13
+ # :reek:TooManyConstants { max_constants: 7 } -- the fixed command of each OS, the message cap and the timeout
14
+ # :reek:TooManyInstanceVariables { max_instance_variables: 5 } -- the injected runner, OS, stream and PowerShell path, and the warned flag
15
+ class Notifier
16
+ MAX = 200
17
+ TIMEOUT = 15
18
+ OSASCRIPT = ['/usr/bin/osascript', '-e', 'on run argv', '-e',
19
+ 'display notification (item 2 of argv) with title (item 1 of argv)', '-e', 'end run', '--'].freeze
20
+ NOTIFY_SEND = ['notify-send', '--app-name=Ruby Raider', '--'].freeze
21
+ MARKUP = { '&' => '&amp;', '<' => '&lt;', '>' => '&gt;' }.freeze
22
+ # Reads the text from the environment and sets it as XML text nodes; one line with no double quotes, so
23
+ # Windows command-line quoting can't split it. Shown under PowerShell's own app id, which Windows accepts.
24
+ TOAST_SCRIPT = [
25
+ "$ErrorActionPreference = 'Stop'",
26
+ '$null = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]',
27
+ '$xml = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)',
28
+ "$texts = $xml.GetElementsByTagName('text')",
29
+ '$null = $texts.Item(0).AppendChild($xml.CreateTextNode($env:RAIDER_NOTIFY_TITLE))',
30
+ '$null = $texts.Item(1).AppendChild($xml.CreateTextNode($env:RAIDER_NOTIFY_MESSAGE))',
31
+ '$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)',
32
+ "[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe').Show($toast)"
33
+ ].join('; ').freeze
34
+ POWERSHELL_ARGS = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', TOAST_SCRIPT].freeze
35
+
36
+ def self.powershell = File.join(ENV.fetch('SystemRoot', 'C:\\Windows'), 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
37
+
38
+ def initialize(runner: Os::CommandRunner.new, host_os: RbConfig::CONFIG['host_os'], err: $stderr, powershell: Notifier.powershell)
39
+ @runner = runner
40
+ @host_os = host_os
41
+ @err = err
42
+ @powershell = powershell
43
+ @warned = false
44
+ end
45
+
46
+ # True when the notification was handed to the desktop
47
+ def notify(title, message)
48
+ title = clean(title)
49
+ message = clean(message)
50
+ result = case @host_os
51
+ when /darwin/ then @runner.call(*OSASCRIPT, title, message, timeout: TIMEOUT)
52
+ when /linux/ then @runner.call(*NOTIFY_SEND, title, message.gsub(/[&<>]/, MARKUP), timeout: TIMEOUT)
53
+ when /mswin|mingw|cygwin/
54
+ @runner.call(@powershell, *POWERSHELL_ARGS, env: { 'RAIDER_NOTIFY_TITLE' => title, 'RAIDER_NOTIFY_MESSAGE' => message },
55
+ timeout: TIMEOUT)
56
+ end
57
+ return false unless result
58
+ return true if result.success?
59
+
60
+ failed(result.stderr)
61
+ rescue StandardError => e
62
+ failed(e.message)
63
+ end
64
+
65
+ private
66
+
67
+ def clean(text) = Schedules.printable(text)[0, MAX].to_s
68
+
69
+ def failed(reason)
70
+ @err.puts("Could not show a desktop notification: #{Schedules.printable(reason.strip)}") unless @warned
71
+ @warned = true
72
+ false
73
+ end
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'open3'
4
+
5
+ module RubyRaider
6
+ module Schedules
7
+ module Os
8
+ # Runs an OS scheduler command (launchctl, schtasks, systemctl, crontab) with no shell. Adapters
9
+ # take one, so tests pass a double and never touch the real scheduler.
10
+ class CommandRunner
11
+ MISSING = 127
12
+ TIMED_OUT = 124
13
+
14
+ # What a command printed and how it exited
15
+ class Result
16
+ attr_reader :stdout, :stderr, :exitstatus
17
+
18
+ def initialize(stdout:, stderr:, exitstatus:)
19
+ @stdout = stdout
20
+ @stderr = stderr
21
+ @exitstatus = exitstatus
22
+ freeze
23
+ end
24
+
25
+ def success? = exitstatus.zero?
26
+ end
27
+
28
+ # [command, command] as the first item keeps even a lone string out of a shell; env adds to the inherited
29
+ # one. With a timeout (seconds) a command still running then is killed and fails.
30
+ def call(*argv, stdin_data: nil, env: {}, timeout: nil)
31
+ command = argv.first.to_s
32
+ Open3.popen3(env, [command, command], *argv.drop(1).map(&:to_s)) do |stdin, stdout, stderr, wait|
33
+ readers = [stdout, stderr].map { |io| reader(io) }
34
+ feed(stdin, stdin_data)
35
+ next timed_out(command, timeout, wait) unless wait.join(timeout)
36
+
37
+ status = wait.value
38
+ Result.new(stdout: readers[0].value, stderr: readers[1].value, exitstatus: status.exitstatus || (128 + status.termsig.to_i))
39
+ end
40
+ rescue SystemCallError => e
41
+ Result.new(stdout: '', stderr: "Could not run #{command}: #{e.message}", exitstatus: MISSING)
42
+ end
43
+
44
+ private
45
+
46
+ # Read in a thread, so a full pipe can't block the command; quiet when the pipe is closed under it
47
+ def reader(io)
48
+ thread = Thread.new { io.read.to_s }
49
+ thread.report_on_exception = false
50
+ thread
51
+ end
52
+
53
+ def feed(stdin, data)
54
+ stdin.write(data.to_s)
55
+ rescue Errno::EPIPE
56
+ nil
57
+ ensure
58
+ stdin.close
59
+ end
60
+
61
+ def timed_out(command, timeout, wait)
62
+ begin
63
+ Process.kill('KILL', wait.pid)
64
+ rescue SystemCallError
65
+ nil
66
+ end
67
+ wait.join
68
+ Result.new(stdout: '', stderr: "#{command} took longer than #{timeout} s", exitstatus: TIMED_OUT)
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,147 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'shellwords'
4
+ require_relative 'command_runner'
5
+ require_relative '../base'
6
+
7
+ module RubyRaider
8
+ module Schedules
9
+ module Os
10
+ # Linux without a systemd user manager: one tagged block per schedule in the user's crontab, read with
11
+ # `crontab -l` and written back with `crontab -`. Every value goes through Shellwords.escape, which also
12
+ # escapes % as \% (cron would turn a bare % into a newline). Lines that are not ours keep every byte.
13
+ class Cron
14
+ CRONTAB = 'crontab'
15
+ # Debian's vixie cron cuts a command at MAX_COMMAND (1000) bytes without a word; stay under it
16
+ MAX_LINE = 990
17
+
18
+ # kind: the Kind whose entries this crontab block holds
19
+ def initialize(kind:, runner: CommandRunner.new)
20
+ @kind = kind
21
+ @runner = runner
22
+ end
23
+
24
+ def label = 'cron'
25
+
26
+ def missed_runs_note = '(cron: missed runs are skipped)'
27
+
28
+ # Minute hour day-of-month month day-of-week (the system time zone), then the command for /bin/sh
29
+ def line(schedule)
30
+ ruby = schedule.ruby
31
+ raise Error, "cron can not run ruby from #{Schedules.printable(ruby)}: env would read the = as a variable" if ruby.include?('=')
32
+
33
+ env = schedule.env.map { |key, value| "#{key}=#{value}" }
34
+ command = ['cd', escape(schedule.working_directory), '&&', '/usr/bin/env', *[*env, *schedule.argv].map { |word| escape(word) },
35
+ '>>', escape(schedule.log_path), '2>&1']
36
+ "#{fields(schedule)} #{command.join(' ')}"
37
+ end
38
+
39
+ # Our block goes first: above any SHELL=, CRON_TZ= or MAILTO= line, and with no byte of the rest changed
40
+ def install(schedule)
41
+ os_id = schedule.os_id
42
+ entry = line(schedule)
43
+ raise Error, "cron can not run #{schedule.name}: its crontab line is #{entry.bytesize} bytes, over #{MAX_LINE}" if entry.bytesize > MAX_LINE
44
+
45
+ rest, = without(read, os_id)
46
+ save("#{@kind.cron_tag}#{os_id}\n#{entry}\n#{rest}")
47
+ true
48
+ end
49
+
50
+ # True when our block was there and is gone, false when it was already gone
51
+ def remove(os_id)
52
+ tag = checked_os_id(os_id)
53
+ rest, found = without(read, tag)
54
+ save(rest) if found
55
+ found
56
+ end
57
+
58
+ def present?(os_id)
59
+ tag = checked_os_id(os_id)
60
+ without(read, tag).last
61
+ end
62
+
63
+ # The os_ids of this kind starting with prefix on our tag lines, sorted
64
+ def list_ids(prefix)
65
+ tag = @kind.cron_tag
66
+ read.dup.force_encoding(Encoding::UTF_8).scrub.each_line.filter_map do |text|
67
+ line = text.chomp
68
+ id = line.delete_prefix(tag)
69
+ id if id != line && @kind.listed?(id, prefix)
70
+ end.uniq.sort
71
+ end
72
+
73
+ # True when crontab -l answers (an empty crontab counts)
74
+ def usable?
75
+ read
76
+ true
77
+ rescue Error
78
+ false
79
+ end
80
+
81
+ private
82
+
83
+ def fields(schedule)
84
+ minute = schedule.minute
85
+ return "#{minute} * * * *" if schedule.every == 'hour'
86
+
87
+ day = case schedule.every
88
+ when 'weekday' then '1-5'
89
+ when 'week' then weekday(schedule.on.to_s).to_s
90
+ else '*'
91
+ end
92
+ "#{minute} #{schedule.hour} * * #{day}"
93
+ end
94
+
95
+ # cron counts Sunday as 0
96
+ def weekday(day)
97
+ index = DAYS.index(day)
98
+ raise Error, "Invalid day #{day.inspect}" unless index
99
+
100
+ (index + 1) % 7
101
+ end
102
+
103
+ def escape(word) = Shellwords.escape(word)
104
+
105
+ # The crontab without any of our tag lines, each with the line after it when that line is our command,
106
+ # and whether a tag was there
107
+ def without(table, os_id)
108
+ tag = "#{@kind.cron_tag}#{os_id}"
109
+ name = @kind.os_id_pattern.match(os_id).to_a[1]
110
+ kept = []
111
+ found = after_tag = false
112
+ table.lines.each do |text|
113
+ ours = text.chomp == tag || (after_tag && our_command?(text, name))
114
+ after_tag = text.chomp == tag
115
+ found ||= after_tag
116
+ kept << text unless ours
117
+ end
118
+ [kept.join, found]
119
+ end
120
+
121
+ # The line under our tag runs `raider <command> run <name> --project ... --trigger schedule`
122
+ def our_command?(text, name) = @kind.our_command?(text, name)
123
+
124
+ def read
125
+ result = @runner.call(CRONTAB, '-l')
126
+ return result.stdout if result.success?
127
+
128
+ stderr = result.stderr.scrub('?')
129
+ return '' if stderr.match?(/no crontab/i)
130
+
131
+ raise Error, "cron could not read the crontab: #{Schedules.printable(stderr.strip)}"
132
+ end
133
+
134
+ def save(table)
135
+ result = @runner.call(CRONTAB, '-', stdin_data: table)
136
+ raise Error, "cron could not save the crontab: #{Schedules.printable(result.stderr.strip)}" unless result.success?
137
+ end
138
+
139
+ def checked_os_id(os_id)
140
+ return os_id if @kind.name_in(os_id)
141
+
142
+ raise Error, "Invalid os_id #{Schedules.printable(os_id.inspect)}: #{@kind.not_ours}"
143
+ end
144
+ end
145
+ end
146
+ end
147
+ end