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,182 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fileutils'
4
+ require 'securerandom'
5
+ require_relative 'command_runner'
6
+ require_relative '../base'
7
+
8
+ module RubyRaider
9
+ module Schedules
10
+ module Os
11
+ # macOS: a LaunchAgent plist in ~/Library/LaunchAgents per schedule, loaded into the user's GUI
12
+ # domain with launchctl. Every value in the plist goes through one XML escaper.
13
+ # :reek:TooManyConstants { max_constants: 5 } -- the two tools, NOFOLLOW, the XML escapes and header
14
+ class Launchd
15
+ LAUNCHCTL = '/bin/launchctl'
16
+ PLUTIL = '/usr/bin/plutil'
17
+ NOFOLLOW = defined?(File::NOFOLLOW) ? File::NOFOLLOW : 0
18
+ ESCAPES = { '&' => '&amp;', '<' => '&lt;', '>' => '&gt;', '"' => '&quot;', "'" => '&apos;' }.freeze
19
+ HEADER = <<~XML
20
+ <?xml version="1.0" encoding="UTF-8"?>
21
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
22
+ <plist version="1.0">
23
+ XML
24
+
25
+ # kind: the Kind whose LaunchAgents this adapter writes and removes
26
+ def initialize(kind:, runner: CommandRunner.new, home: Dir.home, uid: Process.uid)
27
+ @kind = kind
28
+ @runner = runner
29
+ @home = home
30
+ @uid = uid
31
+ end
32
+
33
+ def label = 'launchd'
34
+
35
+ # The LaunchAgent plist for the schedule (local time, no RunAtLoad)
36
+ def plist(schedule)
37
+ path = schedule.log_path
38
+ entries = [
39
+ ['Label', string(schedule.os_id)],
40
+ ['ProgramArguments', array(schedule.argv.map { |arg| string(arg) })],
41
+ ['WorkingDirectory', string(schedule.working_directory)],
42
+ ['StandardOutPath', string(path)],
43
+ ['StandardErrorPath', string(path)],
44
+ ['EnvironmentVariables', dict(schedule.env.map { |key, value| [key, string(value)] })],
45
+ ['StartCalendarInterval', calendar(schedule)]
46
+ ]
47
+ "#{HEADER}#{dict(entries).join("\n")}\n</plist>\n"
48
+ end
49
+
50
+ def plist_path(os_id) = File.join(agents_dir, "#{checked_os_id(os_id)}.plist")
51
+
52
+ # Writes the plist (linted before it replaces anything), then reloads the service
53
+ def install(schedule)
54
+ os_id = schedule.os_id
55
+ path = plist_path(os_id)
56
+ write(path, plist(schedule))
57
+ launchctl('bootout', service(os_id))
58
+ result = launchctl('bootstrap', domain, path)
59
+ return true if result.success?
60
+
61
+ raise Error, "launchd could not load #{os_id}: #{Schedules.printable(result.stderr.strip)}#{discard(path)}"
62
+ end
63
+
64
+ # True when a plist or a loaded service was removed, false when it was already gone. The plist goes
65
+ # first: a job removing itself is ended by its own bootout, and its plist must be gone by then.
66
+ # If the unlink succeeds and the bootout fails, the job stays loaded with no plist until logout.
67
+ def remove(os_id)
68
+ unlinked = unlink(plist_path(os_id))
69
+ unloaded = launchctl('bootout', service(os_id)).success?
70
+ unlinked || unloaded
71
+ end
72
+
73
+ def present?(os_id) = launchctl('print', service(checked_os_id(os_id))).success?
74
+
75
+ # The os_ids of this kind starting with prefix that have a plist, sorted; runs nothing
76
+ def list_ids(prefix)
77
+ dir = agents_dir
78
+ Dir.children(dir).filter_map do |file|
79
+ next unless file.valid_encoding? && file.end_with?('.plist')
80
+
81
+ id = file.delete_suffix('.plist')
82
+ id if @kind.listed?(id, prefix)
83
+ end.sort
84
+ rescue Errno::ENOENT
85
+ []
86
+ rescue SystemCallError => e
87
+ raise Error, "Could not read #{dir}: #{e.message}"
88
+ end
89
+
90
+ private
91
+
92
+ def launchctl(*args) = @runner.call(LAUNCHCTL, *args)
93
+
94
+ def domain = "gui/#{@uid}"
95
+
96
+ def service(os_id) = "#{domain}/#{os_id}"
97
+
98
+ # True when the plist was there; a plist that stays behind is an error, not "already gone"
99
+ def unlink(path)
100
+ File.unlink(path)
101
+ true
102
+ rescue Errno::ENOENT
103
+ false
104
+ rescue SystemCallError => e
105
+ raise Error, "Could not remove #{path}: #{e.message}"
106
+ end
107
+
108
+ def agents_dir = File.join(@home, 'Library', 'LaunchAgents')
109
+
110
+ def checked_os_id(os_id)
111
+ return os_id if @kind.name_in(os_id)
112
+
113
+ raise Error, "Invalid os_id #{Schedules.printable(os_id.inspect)}: #{@kind.not_ours}"
114
+ end
115
+
116
+ def escape(text) = text.to_s.gsub(/[&<>"']/, ESCAPES)
117
+
118
+ def string(text) = ["<string>#{escape(text)}</string>"]
119
+
120
+ def integer(number) = ["<integer>#{Integer(number)}</integer>"]
121
+
122
+ def array(items) = ['<array>', *indent(items.flatten), '</array>']
123
+
124
+ def dict(pairs)
125
+ body = pairs.flat_map { |key, value| ["<key>#{escape(key)}</key>", *value] }
126
+ ['<dict>', *indent(body), '</dict>']
127
+ end
128
+
129
+ def indent(lines) = lines.map { |line| "\t#{line}" }
130
+
131
+ # DAYS runs mon..sun
132
+ def calendar(schedule)
133
+ time = [['Hour', integer(schedule.hour)], ['Minute', integer(schedule.minute)]]
134
+ case schedule.every
135
+ when 'hour' then dict([['Minute', integer(schedule.minute)]])
136
+ when 'day' then dict(time)
137
+ else
138
+ days = schedule.days.map { |day| dict([['Weekday', integer(weekday(day))], *time]) }
139
+ schedule.every == 'week' ? days.first : array(days)
140
+ end
141
+ end
142
+
143
+ # launchd counts Sunday as 0
144
+ def weekday(day)
145
+ index = DAYS.index(day)
146
+ raise Error, "Invalid day #{day.inspect}" unless index
147
+
148
+ (index + 1) % 7
149
+ end
150
+
151
+ # Removes the plist a failed bootstrap left; returns what to add to the error when it stays behind
152
+ def discard(path)
153
+ unlink(path)
154
+ ''
155
+ rescue Error => e
156
+ "; also: #{e.message}"
157
+ end
158
+
159
+ # Temp file in the same folder, checked with plutil, then renamed over the old plist
160
+ def write(path, text)
161
+ dir = File.dirname(path)
162
+ FileUtils.mkdir_p(dir)
163
+ temp = File.join(dir, ".#{File.basename(path)}.#{SecureRandom.hex(6)}.tmp")
164
+ File.open(temp, File::WRONLY | File::CREAT | File::EXCL | NOFOLLOW, 0o644) do |file|
165
+ file.write(text)
166
+ file.flush
167
+ file.fsync
168
+ file.chmod(0o644)
169
+ end
170
+ lint = @runner.call(PLUTIL, '-lint', temp)
171
+ raise Error, "launchd plist for #{File.basename(path)} is invalid: #{Schedules.printable("#{lint.stdout} #{lint.stderr}".strip)}" unless lint.success?
172
+
173
+ File.rename(temp, path)
174
+ rescue SystemCallError => e
175
+ raise Error, "Could not write #{path}: #{e.message}"
176
+ ensure
177
+ FileUtils.rm_f(temp) if temp && File.exist?(temp)
178
+ end
179
+ end
180
+ end
181
+ end
182
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'command_runner'
4
+ require_relative 'systemd'
5
+ require_relative 'cron'
6
+
7
+ module RubyRaider
8
+ module Schedules
9
+ module Os
10
+ # Linux: systemd user timers when the user's systemd manager answers, cron otherwise. A schedule made over
11
+ # ssh (no user bus, so cron) must still go when unscheduled from a desktop session, so remove and present?
12
+ # also look in the other scheduler when it answers. The reverse (a systemd timer, unscheduled where no user
13
+ # bus answers) can only be seen from its unit files, and can only be removed where systemctl --user works.
14
+ class Linux
15
+ def self.pick(runner = CommandRunner.new, kind:) = new(kind: kind, runner: runner)
16
+
17
+ # kind: the Kind of the schedules this adapter installs and removes
18
+ def initialize(kind:, runner: CommandRunner.new, systemd: Systemd.new(kind: kind, runner: runner), cron: Cron.new(kind: kind, runner: runner))
19
+ @kind = kind
20
+ # systemd is the other one only when it answers, so with cron first there is no other one
21
+ @systemd = systemd
22
+ @primary, @other = systemd.usable? ? [systemd, cron] : [cron, nil]
23
+ end
24
+
25
+ def label = @primary.label
26
+
27
+ def missed_runs_note = @primary.missed_runs_note
28
+
29
+ def install(schedule) = @primary.install(schedule)
30
+
31
+ # True when either scheduler removed something
32
+ def remove(os_id)
33
+ removed = @primary.remove(os_id)
34
+ other = @other
35
+ other_removed = other&.usable? ? other.remove(os_id) : false
36
+ refuse_stranded(os_id)
37
+ removed || other_removed
38
+ end
39
+
40
+ # True when either scheduler has it, or systemd unit files are there though systemd does not answer
41
+ def present?(os_id) = @primary.present?(os_id) || other_present?(os_id) || stranded?(os_id)
42
+
43
+ # Both schedulers' ids plus systemd unit files (there even when systemd does not answer); only the
44
+ # primary scheduler failing is an error
45
+ def list_ids(prefix)
46
+ (@primary.list_ids(prefix) + other_ids(prefix) + quietly { @systemd.list_ids(prefix) }).uniq.sort
47
+ end
48
+
49
+ private
50
+
51
+ def other_ids(prefix)
52
+ other = @other
53
+ other&.usable? ? quietly { other.list_ids(prefix) } : []
54
+ end
55
+
56
+ def quietly
57
+ yield
58
+ rescue Error
59
+ []
60
+ end
61
+
62
+ def stranded?(os_id) = @primary != @systemd && @systemd.unit_files?(os_id)
63
+
64
+ # Raises so the schedules.yml entry stays until the timer can really go
65
+ def refuse_stranded(os_id)
66
+ return unless stranded?(os_id)
67
+
68
+ raise Error, @kind.stranded(os_id.split('.').last)
69
+ end
70
+
71
+ # The other scheduler failing counts as not there
72
+ def other_present?(os_id)
73
+ other = @other
74
+ other&.usable? ? other.present?(os_id) : false
75
+ rescue Error
76
+ false
77
+ end
78
+ end
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,194 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fileutils'
4
+ require 'securerandom'
5
+ require_relative 'command_runner'
6
+ require_relative '../base'
7
+
8
+ module RubyRaider
9
+ module Schedules
10
+ module Os
11
+ # Linux: a oneshot service and a persistent timer per schedule in the user's systemd folder, enabled
12
+ # with systemctl --user. Words in ExecStart= and Environment= are double-quoted with C escapes; every
13
+ # value has % doubled (specifiers) and ExecStart= also has $ doubled (variable expansion).
14
+ # :reek:TooManyConstants { max_constants: 5 } -- the tool, NOFOLLOW, the escapes, the calendar days, the path rule
15
+ class Systemd
16
+ SYSTEMCTL = 'systemctl'
17
+ NOFOLLOW = defined?(File::NOFOLLOW) ? File::NOFOLLOW : 0
18
+ QUOTED = { '\\' => '\\\\', '"' => '\\"', '%' => '%%' }.freeze
19
+ CALENDAR = { 'hour' => '', 'day' => '', 'weekday' => 'Mon..Fri ' }.freeze
20
+ # The unit parser strips whitespace at the ends of a value and reads a trailing backslash as "continued"
21
+ UNSAFE_PATH = /\s\z|\\\z/
22
+
23
+ # kind: the Kind whose units this adapter writes and removes
24
+ def initialize(kind:, runner: CommandRunner.new, home: Dir.home, config_home: ENV.fetch('XDG_CONFIG_HOME', nil))
25
+ @kind = kind
26
+ @runner = runner
27
+ @home = home
28
+ @config_home = config_home
29
+ end
30
+
31
+ def label = 'systemd'
32
+
33
+ def missed_runs_note = nil
34
+
35
+ def service(schedule)
36
+ env = schedule.env.map { |key, value| "Environment=#{quote("#{key}=#{value}")}" }
37
+ exec = schedule.argv.map { |arg| quote(arg.gsub('$', '$$')) }.join(' ')
38
+ log = specifiers(schedule.log_path)
39
+ <<~UNIT
40
+ [Unit]
41
+ Description=#{@kind.service_description(schedule.name)}
42
+
43
+ [Service]
44
+ Type=oneshot
45
+ WorkingDirectory=#{specifiers(schedule.working_directory)}
46
+ #{env.join("\n")}
47
+ ExecStart=#{exec}
48
+ StandardOutput=append:#{log}
49
+ StandardError=append:#{log}
50
+ UNIT
51
+ end
52
+
53
+ # Local time; Persistent= runs a missed time once the user manager is back
54
+ def timer(schedule)
55
+ every = schedule.every
56
+ day = CALENDAR.fetch(every) { "#{schedule.on.to_s.capitalize} " }
57
+ hour = every == 'hour' ? '*' : format('%02d', schedule.hour)
58
+ <<~UNIT
59
+ [Unit]
60
+ Description=#{@kind.timer_description(schedule.name)}
61
+
62
+ [Timer]
63
+ OnCalendar=#{day}*-*-* #{hour}:#{format('%02d', schedule.minute)}:00
64
+ Persistent=true
65
+
66
+ [Install]
67
+ WantedBy=timers.target
68
+ UNIT
69
+ end
70
+
71
+ def unit_path(os_id, unit) = File.join(units_dir, "#{checked_os_id(os_id)}.#{unit}")
72
+
73
+ # Writes both units (temp files renamed into place), reloads and enables the timer; a failure leaves no unit behind
74
+ def install(schedule)
75
+ os_id = schedule.os_id
76
+ [schedule.working_directory, schedule.log_path].each { |path| checked_path(path) }
77
+ write({ unit_path(os_id, 'service') => service(schedule), unit_path(os_id, 'timer') => timer(schedule) })
78
+ failure = [systemctl('daemon-reload'), systemctl('enable', '--now', "#{os_id}.timer")].find { |result| !result.success? }
79
+ return true unless failure
80
+
81
+ message = "systemd could not enable #{os_id}: #{Schedules.printable(failure.stderr.strip)}"
82
+ raise Error, "#{message}#{discard(os_id)}"
83
+ end
84
+
85
+ # True when a unit file was removed, false when it was already gone
86
+ def remove(os_id)
87
+ paths = %w[service timer].map { |unit| unit_path(os_id, unit) }
88
+ systemctl('disable', '--now', "#{os_id}.timer")
89
+ removed = paths.map { |path| unlink(path) }.any?
90
+ reload = systemctl('daemon-reload')
91
+ raise Error, "systemd could not reload after removing #{os_id}: #{Schedules.printable(reload.stderr.strip)}" unless reload.success?
92
+
93
+ removed
94
+ end
95
+
96
+ def present?(os_id) = systemctl('is-enabled', "#{checked_os_id(os_id)}.timer").success?
97
+
98
+ # The os_ids of this kind starting with prefix that have a unit file, sorted (no user manager needed)
99
+ def list_ids(prefix)
100
+ dir = units_dir
101
+ Dir.children(dir).filter_map do |file|
102
+ next unless file.valid_encoding?
103
+
104
+ id = file.sub(/\.(?:service|timer)\z/, '')
105
+ id if id != file && @kind.listed?(id, prefix)
106
+ end.uniq.sort
107
+ rescue Errno::ENOENT
108
+ []
109
+ rescue SystemCallError => e
110
+ raise Error, "Could not read #{dir}: #{e.message}"
111
+ end
112
+
113
+ # True when a unit file for the schedule is on disk (no user manager needed)
114
+ def unit_files?(os_id) = %w[service timer].any? { |unit| File.exist?(unit_path(os_id, unit)) }
115
+
116
+ # True when the user's systemd manager answers
117
+ def usable? = systemctl('show-environment').success?
118
+
119
+ private
120
+
121
+ def systemctl(*args) = @runner.call(SYSTEMCTL, '--user', *args)
122
+
123
+ def units_dir
124
+ config = @config_home
125
+ base = config.is_a?(String) && File.absolute_path?(config) ? config : File.join(@home, '.config')
126
+ File.join(base, 'systemd', 'user')
127
+ end
128
+
129
+ def checked_os_id(os_id)
130
+ return os_id if @kind.name_in(os_id)
131
+
132
+ raise Error, "Invalid os_id #{Schedules.printable(os_id.inspect)}: #{@kind.not_ours}"
133
+ end
134
+
135
+ def checked_path(path)
136
+ raise Error, "systemd can not use the path #{Schedules.printable(path.inspect)}: it ends in whitespace or a backslash" if UNSAFE_PATH.match?(path)
137
+ end
138
+
139
+ # A word systemd gives back exactly: double quotes, \\ and \" escapes, %% for %
140
+ def quote(text) = %("#{text.gsub(/[\\"%]/, QUOTED)}")
141
+
142
+ # A raw path value: only specifiers apply
143
+ def specifiers(text) = text.gsub('%', '%%')
144
+
145
+ # True when the file was there; a unit that stays behind is an error, not "already gone"
146
+ def unlink(path)
147
+ File.unlink(path)
148
+ true
149
+ rescue Errno::ENOENT
150
+ false
151
+ rescue SystemCallError => e
152
+ raise Error, "Could not remove #{path}: #{e.message}"
153
+ end
154
+
155
+ # Disables the timer, removes both units and reloads; returns what to add to the error when that fails too
156
+ def discard(os_id)
157
+ systemctl('disable', "#{os_id}.timer")
158
+ %w[service timer].each { |unit| unlink(unit_path(os_id, unit)) }
159
+ reload = systemctl('daemon-reload')
160
+ reload.success? ? '' : "; also: reload failed: #{Schedules.printable(reload.stderr.strip)}"
161
+ rescue Error => e
162
+ "; also: #{e.message}"
163
+ end
164
+
165
+ # Every temp file is written before any unit is replaced, so a failed write changes nothing
166
+ def write(texts)
167
+ temps = {}
168
+ texts.each { |path, text| temps[path] = temp_file(path, text) }
169
+ temps.each { |path, temp| File.rename(temp, path) }
170
+ rescue SystemCallError => e
171
+ raise Error, "Could not write the systemd units in #{units_dir}: #{e.message}"
172
+ ensure
173
+ temps&.each_value { |temp| FileUtils.rm_f(temp) if File.exist?(temp) }
174
+ end
175
+
176
+ def temp_file(path, text)
177
+ dir = File.dirname(path)
178
+ FileUtils.mkdir_p(dir)
179
+ temp = File.join(dir, ".#{File.basename(path)}.#{SecureRandom.hex(6)}.tmp")
180
+ File.open(temp, File::WRONLY | File::CREAT | File::EXCL | NOFOLLOW, 0o644) do |file|
181
+ file.write(text)
182
+ file.flush
183
+ file.fsync
184
+ file.chmod(0o644)
185
+ end
186
+ temp
187
+ rescue SystemCallError
188
+ FileUtils.rm_f(temp) if temp && File.file?(temp)
189
+ raise
190
+ end
191
+ end
192
+ end
193
+ end
194
+ end
@@ -0,0 +1,195 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'tempfile'
4
+ require_relative 'command_runner'
5
+ require_relative '../base'
6
+ require_relative '../next_run'
7
+
8
+ module RubyRaider
9
+ module Schedules
10
+ module Os
11
+ # Windows: one task per schedule in the \RubyRaider\ folder, registered from task XML with schtasks.
12
+ # The task runs ruby.exe directly (never cmd.exe or powershell), with the user's own environment and
13
+ # no log file: the outcome lives in runs.jsonl like any scheduled run. Argument values get Windows CRT
14
+ # quoting, then every value in the XML goes through one XML escaper.
15
+ # Task Scheduler expands %NAME% in Command, Arguments and WorkingDirectory with no escape, so a value
16
+ # holding one is refused before schtasks runs.
17
+ # :reek:TooManyConstants { max_constants: 8 } -- the folder, the XML escapes and namespace, quoting, globs, %NAME%, day names, list rows
18
+ class TaskScheduler
19
+ FOLDER = '\\RubyRaider\\'
20
+ ESCAPES = { '&' => '&amp;', '<' => '&lt;', '>' => '&gt;', '"' => '&quot;', "'" => '&apos;' }.freeze
21
+ NAMESPACE = 'http://schemas.microsoft.com/windows/2004/02/mit/task'
22
+ # ruby.exe reads its own command line (w32_cmdvector in win32.c): ' quotes too, and a * ? [ { outside
23
+ # '...' (even inside "...") makes it glob the argument
24
+ NEEDS_QUOTES = /[ \t\n\v"']/
25
+ GLOB = /[*?\[{]/
26
+ EXPANDS = /%[^%]+%/
27
+ DAY_NAMES = %w[Monday Tuesday Wednesday Thursday Friday Saturday Sunday].freeze
28
+ # A /Query /FO CSV row of a task right in our folder: its name, which our ids never quote or escape
29
+ ROW = /\A"#{Regexp.escape(FOLDER)}([^"\\]*)",/
30
+
31
+ # One argument as ruby.exe reads it back (w32_cmdvector). With a glob character: '...', where nothing
32
+ # is special and nothing globs (and with a ' too: refused). Otherwise "..." when empty or holding
33
+ # whitespace or a quote: backslashes before " (or the closing ") are doubled plus one escapes the ",
34
+ # and an odd run before ' becomes 2n+1 (ruby.exe eats (n+1)/2 of them; an even run is kept as is).
35
+ def self.quote(arg)
36
+ return glob_quote(arg) if arg.match?(GLOB)
37
+ return arg if !arg.empty? && !arg.match?(NEEDS_QUOTES)
38
+
39
+ body = arg.gsub(/(\\*)"/) { "#{Regexp.last_match(1).to_s * 2}\\\"" }
40
+ .gsub(/(\\+)'/) { "#{odd_doubled(Regexp.last_match(1).to_s)}'" }
41
+ .sub(/(\\+)\z/) { Regexp.last_match(1).to_s * 2 }
42
+ "\"#{body}\""
43
+ end
44
+
45
+ def self.glob_quote(arg)
46
+ return "'#{arg}'" unless arg.include?("'")
47
+
48
+ raise Error, "Task Scheduler can not pass #{Schedules.printable(arg.inspect)} to ruby.exe: an argument with both ' and * ? [ or { would be globbed"
49
+ end
50
+
51
+ def self.odd_doubled(slashes) = slashes.length.odd? ? "#{slashes * 2}\\" : slashes
52
+
53
+ def self.join(args) = args.map { |arg| quote(arg) }.join(' ')
54
+
55
+ # kind: the Kind whose tasks this adapter registers and deletes
56
+ def initialize(kind:, runner: CommandRunner.new, clock: Time, schtasks: File.join(ENV.fetch('SystemRoot', 'C:\\Windows'), 'System32', 'schtasks.exe'))
57
+ @kind = kind
58
+ @runner = runner
59
+ @clock = clock
60
+ @schtasks = schtasks
61
+ end
62
+
63
+ def label = 'Task Scheduler'
64
+
65
+ def task_name(os_id) = "#{FOLDER}#{checked_os_id(os_id)}"
66
+
67
+ # The task XML (a UTF-8 String; install writes it as UTF-16LE with a BOM)
68
+ def task_xml(schedule)
69
+ refuse_expansion(schedule)
70
+ body = [
71
+ element('RegistrationInfo', [text('Description', @kind.task_description(schedule.name, schedule.rule_text)),
72
+ text('URI', task_name(schedule.os_id))]),
73
+ element('Triggers', element('CalendarTrigger', trigger(schedule))),
74
+ element('Principals', element('Principal id="Author"', [text('LogonType', 'InteractiveToken'), text('RunLevel', 'LeastPrivilege')])),
75
+ element('Settings', settings),
76
+ element('Actions Context="Author"', element('Exec', action(schedule)))
77
+ ]
78
+ lines = ['<?xml version="1.0" encoding="UTF-16"?>', %(<Task version="1.2" xmlns="#{NAMESPACE}">), *indent(body.flatten), '</Task>']
79
+ "#{lines.join("\n")}\n"
80
+ end
81
+
82
+ # Registers (or replaces) the task from a UTF-16LE temp file, deleted whatever happens
83
+ def install(schedule)
84
+ os_id = schedule.os_id
85
+ file = Tempfile.new([@kind.task_file_prefix, '.xml'], binmode: true)
86
+ file.write("\uFEFF#{task_xml(schedule)}".encode(Encoding::UTF_16LE))
87
+ file.close
88
+ result = schtasks('/Create', '/TN', task_name(os_id), '/XML', file.path.to_s, '/F')
89
+ return true if result.success?
90
+
91
+ raise Error, "Task Scheduler could not create #{os_id}: #{Schedules.printable(result.stderr.strip)}"
92
+ ensure
93
+ file&.close!
94
+ end
95
+
96
+ # True when the task was deleted, false when it was already gone. schtasks words "not found" in
97
+ # the system language, so a failed delete is checked against the task list; a list that can not
98
+ # be read, or still shows the task, is an error.
99
+ def remove(os_id)
100
+ name = task_name(os_id)
101
+ result = schtasks('/Delete', '/TN', name, '/F')
102
+ return true if result.success?
103
+
104
+ listing = list
105
+ return false if listing.success? && !listed?(listing.stdout, name)
106
+
107
+ raise Error, "Task Scheduler could not delete #{os_id}: #{Schedules.printable(result.stderr.strip)}"
108
+ end
109
+
110
+ def present?(os_id)
111
+ name = task_name(os_id)
112
+ listed?(tasks, name)
113
+ end
114
+
115
+ # The os_ids of this kind starting with prefix that are tasks in \\RubyRaider\\, sorted (one query)
116
+ def list_ids(prefix)
117
+ tasks.dup.force_encoding(Encoding::UTF_8).scrub.each_line.filter_map do |row|
118
+ id = row[ROW, 1]
119
+ id if @kind.listed?(id, prefix)
120
+ end.uniq.sort
121
+ end
122
+
123
+ private
124
+
125
+ def schtasks(*args) = @runner.call(@schtasks, *args)
126
+
127
+ # Every task, one CSV row each, the full task name in the first field
128
+ def list = schtasks('/Query', '/FO', 'CSV', '/NH')
129
+
130
+ # The task list's text; an Error when it can't be read
131
+ def tasks
132
+ listing = list
133
+ return listing.stdout if listing.success?
134
+
135
+ raise Error, "Task Scheduler could not list tasks: #{Schedules.printable(listing.stderr.strip)}"
136
+ end
137
+
138
+ def listed?(text, name) = text.each_line.any? { |line| line.start_with?(%("#{name}",)) }
139
+
140
+ def refuse_expansion(schedule)
141
+ # The joined Arguments, as Task Scheduler expands them: a %...% can span two arguments
142
+ value = [schedule.ruby, self.class.join(schedule.argv.drop(1)), schedule.working_directory].find { |item| item.match?(EXPANDS) }
143
+ return unless value
144
+
145
+ raise Error, "Task Scheduler would expand #{Schedules.printable(value[EXPANDS])} as an environment variable in #{Schedules.printable(value.inspect)}: " \
146
+ 'remove the %...% from it'
147
+ end
148
+
149
+ def checked_os_id(os_id)
150
+ return os_id if @kind.name_in(os_id)
151
+
152
+ raise Error, "Invalid os_id #{Schedules.printable(os_id.inspect)}: #{@kind.not_ours}"
153
+ end
154
+
155
+ def escape(value) = value.to_s.gsub(/[&<>"']/, ESCAPES)
156
+
157
+ def text(name, value) = ["<#{name}>#{escape(value)}</#{name}>"]
158
+
159
+ # tag may carry fixed attributes ('Principal id="Author"'); the closing tag is its first word
160
+ def element(tag, children) = ["<#{tag}>", *indent(children.flatten), "</#{tag.split.first}>"]
161
+
162
+ def indent(lines) = lines.map { |line| " #{line}" }
163
+
164
+ # Local time without an offset, never in the past (StartWhenAvailable would run a missed start at
165
+ # once): the next run's date, at the rule's own HH:MM so a DST-shifted next run does not move the
166
+ # daily time; an hour rule starts at its next run.
167
+ def trigger(schedule)
168
+ every = schedule.every
169
+ next_run = NextRun.after(schedule, @clock.now)
170
+ hour = every == 'hour' ? next_run.hour : schedule.hour
171
+ start = format('%<date>sT%<hour>02d:%<minute>02d:00', date: next_run.strftime('%Y-%m-%d'), hour: hour, minute: schedule.minute)
172
+ repeat = every == 'hour' ? [element('Repetition', [text('Interval', 'PT1H'), text('Duration', 'P1D')])] : []
173
+ [*repeat, text('StartBoundary', start), text('Enabled', 'true'), *calendar(schedule, every)]
174
+ end
175
+
176
+ def calendar(schedule, every)
177
+ return element('ScheduleByDay', text('DaysInterval', '1')) if %w[hour day].include?(every)
178
+
179
+ days = schedule.days.map { |day| ["<#{DAY_NAMES.fetch(DAYS.index(day).to_i)} />"] }
180
+ element('ScheduleByWeek', [element('DaysOfWeek', days), text('WeeksInterval', '1')])
181
+ end
182
+
183
+ def settings
184
+ [text('MultipleInstancesPolicy', 'IgnoreNew'), text('DisallowStartIfOnBatteries', 'false'),
185
+ text('StopIfGoingOnBatteries', 'false'), text('StartWhenAvailable', 'true'), text('Enabled', 'true')]
186
+ end
187
+
188
+ def action(schedule)
189
+ ruby, *args = schedule.argv
190
+ [text('Command', ruby), text('Arguments', self.class.join(args)), text('WorkingDirectory', schedule.working_directory)]
191
+ end
192
+ end
193
+ end
194
+ end
195
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'base'
4
+
5
+ module RubyRaider
6
+ module Schedules
7
+ # The schedules of one project and kind that the OS scheduler has, by enumerating it for the project's
8
+ # os_id prefix ("<kind prefix>.<hash10>."). Every id is checked again here, so another project's, another
9
+ # kind's or a malformed id never becomes a name. An OS scheduler that can't be read gives none.
10
+ class OsEnumerator
11
+ # schedule_class: a Rule subclass (its Kind and os_id_prefix_for); root: the project's real path
12
+ def initialize(adapter, schedule_class:, root:)
13
+ @adapter = adapter
14
+ @kind = schedule_class.kind
15
+ @prefix = schedule_class.os_id_prefix_for(root)
16
+ end
17
+
18
+ # The names, sorted and once each
19
+ def names
20
+ adapter = @adapter
21
+ return [] unless adapter.respond_to?(:list_ids)
22
+
23
+ prefix = @prefix
24
+ Array(adapter.list_ids(prefix)).filter_map { |os_id| @kind.name_in(os_id) if @kind.listed?(os_id, prefix) }.uniq.sort
25
+ rescue Error
26
+ []
27
+ end
28
+ end
29
+ end
30
+ end