Class: Koch::SystemdTimerService
- Defined in:
- lib/koch/systemd_timer_service.rb
Overview
A systemd service that is triggered by a timer
Instance Attribute Summary
Attributes inherited from Resource
Instance Method Summary collapse
-
#apply! ⇒ Object
rubocop:disable Metrics/AbcSize rubocop:disable Metrics/MethodLength rubocop:disable Metrics/CyclomaticComplexity rubocop:disable Metrics/PerceivedComplexity.
-
#initialize(name) ⇒ SystemdTimerService
constructor
A new instance of SystemdTimerService.
Methods inherited from Resource
Constructor Details
#initialize(name) ⇒ SystemdTimerService
Returns a new instance of SystemdTimerService.
11 12 13 14 15 16 17 18 |
# File 'lib/koch/systemd_timer_service.rb', line 11 def initialize(name) super # Pick a pseudo-random time between 00:00 and 06:00 (360 minutes) hash = Zlib.crc32(name) % 360 hour = hash / 60 minute = hash % 60 @timer = format("OnCalendar=%02d:%02d", hour, minute) end |
Instance Method Details
#apply! ⇒ Object
rubocop:disable Metrics/AbcSize rubocop:disable Metrics/MethodLength rubocop:disable Metrics/CyclomaticComplexity rubocop:disable Metrics/PerceivedComplexity
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/koch/systemd_timer_service.rb', line 24 def apply! fatal "Systemd services require contents." if contents.nil? name_prefix = "/etc/systemd/system/#{name}" old_contents = begin File.read("#{name_prefix}.service") rescue Errno::ENOENT nil end old_timer_contents = begin File.read("#{name_prefix}.timer") rescue Errno::ENOENT nil end new_timer_contents = <<~TIMER [Unit] Description=Run #{name} regularly [Timer] #{@timer} [Install] WantedBy=timers.target TIMER if old_contents == contents && old_timer_contents == new_timer_contents debug "Systemd #{name} service and timer unchanged" return end @changed = true if old_contents != contents info "Diff for Systemd service #{name}:" info diff(old_contents, contents) maybe("Changed Systemd service #{name}") do File.write("#{name_prefix}.service", contents) end end if old_timer_contents != new_timer_contents info "Diff for Systemd timer #{name}:" info diff(old_timer_contents, new_timer_contents) maybe("Changed Systemd timer #{name}") do File.write("#{name_prefix}.timer", new_timer_contents) end end if system("systemctl is-enabled --quiet #{name}.timer") maybe "systemctl daemon-reload" else maybe "systemctl enable --now #{name}.timer" end end |