fork/home-manager

git clone https://git.julia.blue/fork/home-manager

Robert HelgessonRevert "systemd: use sd-switch"223e3c38

master
6.6 KiB216 linesraw
1require 'set'
2require 'open3'
3
4@dry_run = ENV['DRY_RUN']
5@verbose = ENV['VERBOSE']
6
7UnitsDir = 'home-files/.config/systemd/user'
8
9# 1. Stop all services from the old generation that are not present in the new generation.
10# 2. Ensure all services from the new generation that are wanted by active targets are running:
11#    - Start services that are not already running.
12#    - Restart services whose unit config files have changed between generations.
13# 3. If any services were (re)started, wait 'start_timeout_ms' and report services
14#    that failed to start. This helps debugging quickly failing services.
15#
16# Whenever service failures are detected, show the output of
17# 'systemd --user status' for the affected services.
18#
19def setup_services(old_gen_path, new_gen_path, start_timeout_ms_string)
20  start_timeout_ms = start_timeout_ms_string.to_i
21
22  old_units_path = File.join(old_gen_path, UnitsDir) unless old_gen_path.empty?
23  new_units_path = File.join(new_gen_path, UnitsDir)
24
25  old_services = get_services(old_units_path)
26  new_services = get_services(new_units_path)
27
28  exit if old_services.empty? && new_services.empty?
29
30  all_services = get_active_targets_units(new_units_path)
31  maybe_changed = all_services & old_services
32  changed_services = get_changed_services(old_units_path, new_units_path, maybe_changed)
33  unchanged_oneshots = get_oneshot_services(maybe_changed - changed_services)
34
35  # These services should be running when this script is finished
36  services_to_run = all_services - unchanged_oneshots
37
38  # Only stop active services, otherwise we might get a 'service not loaded' error
39  # for inactive services that were removed in the current generation.
40  to_stop = get_active_units(old_services - new_services)
41  to_restart = changed_services
42  to_start = get_inactive_units(services_to_run - to_restart)
43
44  raise "daemon-reload failed" unless run_cmd('systemctl', '--user', 'daemon-reload')
45
46  # Exclude units that shouldn't be (re)started or stopped
47  no_manual_start, no_manual_stop, no_restart = get_restricted_units(to_stop + to_restart + to_start)
48  notify_skipped_units(to_restart & no_restart)
49  to_stop -= no_manual_stop
50  to_restart -= no_manual_stop + no_manual_start + no_restart
51  to_start -= no_manual_start
52
53  if to_stop.empty? && to_start.empty? && to_restart.empty?
54    print_service_msg("All services are already running", services_to_run)
55  else
56    puts "Setting up services" if @verbose
57    systemctl_action('stop', to_stop)
58    systemctl_action('start', to_start)
59    systemctl_action('restart', to_restart)
60    started_services = to_start + to_restart
61    if start_timeout_ms > 0 && !started_services.empty? && !@dry_run
62      failed = wait_and_get_failed_services(started_services, start_timeout_ms)
63      if failed.empty?
64        print_service_msg("All services are running", services_to_run)
65      else
66        puts
67        puts "Error. These services failed to start:", failed
68        show_failed_services_status(failed)
69        exit 1
70      end
71    end
72  end
73end
74
75def get_services(dir)
76  services = get_service_files(dir) if dir && Dir.exists?(dir)
77  Set.new(services)
78end
79
80def get_service_files(dir)
81  Dir.chdir(dir) { Dir['*[^@].{service,socket,timer}'] }
82end
83
84def get_changed_services(dir_a, dir_b, services)
85  services.select do |service|
86    a = File.join(dir_a, service)
87    b = File.join(dir_b, service)
88    (File.size(a) != File.size(b)) || (File.read(a) != File.read(b))
89  end
90end
91
92TargetDirRegexp = /^(.*\.target)\.wants$/
93
94# @return all units wanted by active targets
95def get_active_targets_units(units_dir)
96  return Set.new unless Dir.exists?(units_dir)
97  targets = Dir.entries(units_dir).map { |entry| entry[TargetDirRegexp, 1] }.compact
98  active_targets = get_active_units(targets)
99  active_units = active_targets.map do |target|
100    get_service_files(File.join(units_dir, "#{target}.wants"))
101  end.flatten
102  Set.new(active_units)
103end
104
105# @return true on success
106def run_cmd(*cmd)
107  print_cmd cmd
108  @dry_run || system(*cmd)
109end
110
111def systemctl_action(cmd, services)
112  return if services.empty?
113
114  verb = (cmd == 'stop') ? 'Stopping' : "#{cmd.capitalize}ing"
115  puts "#{verb}: #{services.join(' ')}"
116
117  cmd = ['systemctl', '--user', cmd, *services]
118  if @dry_run
119    puts cmd.join(' ')
120    return
121  end
122
123  output, status = Open3.capture2e(*cmd)
124  print output
125  # Show status for failed services
126  unless status.success?
127    # Due to a bug in systemd, the '--user' argument is not always provided
128    output.scan(/systemctl (?:--user )?(status .*?)['"]/).flatten.each do |status_cmd|
129      puts
130      run_cmd("systemctl --user #{status_cmd}")
131    end
132    exit 1
133  end
134end
135
136def systemctl(*cmd)
137  output, _ = Open3.capture2('systemctl', '--user', *cmd)
138  output
139end
140
141def print_cmd(cmd)
142  puts [*cmd].join(' ') if @verbose || @dry_run
143end
144
145def get_active_units(units)
146  filter_units(units) { |state| state == 'active' }
147end
148
149def get_inactive_units(units)
150  filter_units(units) { |state| state != 'active' }
151end
152
153def get_failed_units(units)
154  filter_units(units) { |state| state == 'failed' }
155end
156
157def filter_units(units)
158  return [] if units.empty?
159  states = systemctl('is-active', *units).split
160  units.select.with_index { |_, i| yield states[i] }
161end
162
163def get_oneshot_services(units)
164  return [] if units.empty?
165  types = systemctl('show', '-p', 'Type', *units).split
166  units.select.with_index do |_, i|
167    types[i] == 'Type=oneshot'
168  end
169end
170
171def get_restricted_units(units)
172  infos = systemctl('show', '-p', 'RefuseManualStart', '-p', 'RefuseManualStop', *units)
173          .split("\n\n")
174  no_manual_start = []
175  no_manual_stop = []
176  infos.zip(units).each do |info, unit|
177    no_start, no_stop = info.split("\n")
178    no_manual_start << unit if no_start.end_with?('yes')
179    no_manual_stop << unit if no_stop.end_with?('yes')
180  end
181  # Get units that should not be restarted even if a change has been detected.
182  no_restart_regexp = /^\s*X-RestartIfChanged\s*=\s*false\b/
183  no_restart = units.select { |unit| systemctl('cat', unit) =~ no_restart_regexp }
184  [no_manual_start, no_manual_stop, no_restart]
185end
186
187def wait_and_get_failed_services(services, start_timeout_ms)
188  puts "Waiting #{start_timeout_ms} ms for services to fail"
189  # Force the previous message to always be visible before sleeping
190  STDOUT.flush
191  sleep(start_timeout_ms / 1000.0)
192  get_failed_units(services)
193end
194
195def show_failed_services_status(services)
196  puts
197  services.each do |service|
198    run_cmd('systemctl', '--user', 'status', service)
199    puts
200  end
201end
202
203def print_service_msg(msg, services)
204  return if services.empty?
205  if @verbose
206    puts "#{msg}:", services.to_a
207  else
208    puts msg
209  end
210end
211
212def notify_skipped_units(no_restart)
213  puts "Not restarting: #{no_restart.join(' ')}" unless no_restart.empty?
214end
215
216setup_services(*ARGV)