Module: Homebrew::Services::Cli Private

Extended by:
FileUtils
Defined in:
services/cli.rb

This module is part of a private API. This module may only be used in the Homebrew/brew repository. Third parties should avoid using this module if possible, as it may be removed or changed without warning.

Class Method Summary collapse

Class Method Details

.binString

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Binary name.

Returns:



23
24
25
# File 'services/cli.rb', line 23

def self.bin
  "brew services"
end

.check(targets) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Check if formula has been found.

Raises:



44
45
46
47
48
# File 'services/cli.rb', line 44

def self.check(targets)
  raise UsageError, "Formula(e) missing, please provide a formula name or use --all" if targets.empty?

  true
end

.install_service_file(service, file) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Raises:



356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'services/cli.rb', line 356

def self.install_service_file(service, file)
  raise UsageError, "Formula `#{service.name}` is not installed" unless service.installed?

  unless service.service_file.exist?
    raise UsageError,
          "Formula `#{service.name}` has not implemented #plist, #service or installed a locatable service file"
  end

  temp = Tempfile.new(service.service_name)
  temp << if file.blank?
    contents = service.service_file.read

    if sudo_service_user && System.launchctl?
      # set the username in the new plist file
      ohai "Setting username in #{service.service_name} to #{System.user}"
      plist_data = Plist.parse_xml(contents, marshal: false)
      plist_data["UserName"] = sudo_service_user
      plist_data.to_plist
    else
      contents
    end
  else
    file.read
  end
  temp.flush

  rm service.dest if service.dest.exist?
  service.dest_dir.mkpath unless service.dest_dir.directory?
  cp T.must(temp.path), service.dest

  # Clear tempfile.
  temp.close

  chmod 0644, service.dest

  System::Systemctl.run("daemon-reload") if System.systemctl?
end

.kill(targets, verbose: false) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Stop a service but keep it registered.

Parameters:



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'services/cli.rb', line 228

def self.kill(targets, verbose: false)
  targets.each do |service|
    if !service.pid?
      puts "Service `#{service.name}` is not started."
    elsif service.keep_alive?
      puts "Service `#{service.name}` is set to automatically restart and can't be killed."
    else
      puts "Killing `#{service.name}`... (might take a while)"
      if System.systemctl?
        System::Systemctl.quiet_run("stop", service.service_name)
      elsif System.launchctl?
        quiet_system System.launchctl, "stop", "#{System.domain_target}/#{service.service_name}"
      end

      if service.pid?
        opoo "Unable to kill `#{service.name}` (label: #{service.service_name})"
      else
        ohai "Successfully killed `#{service.name}` (label: #{service.service_name})"
      end
    end
  end
end

.kill_orphaned_servicesObject

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Kill services that don't have a service file



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'services/cli.rb', line 51

def self.kill_orphaned_services
  cleaned_labels = []
  cleaned_services = []
  running.each do |label|
    if (service = FormulaWrapper.from(label))
      unless service.dest.file?
        cleaned_labels << label
        cleaned_services << service
      end
    else
      opoo "Service #{label} not managed by `#{bin}` => skipping"
    end
  end
  kill(cleaned_services)
  cleaned_labels
end

.launchctl_load(service, file:, enable:) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:



323
324
325
326
# File 'services/cli.rb', line 323

def self.launchctl_load(service, file:, enable:)
  safe_system System.launchctl, "enable", "#{System.domain_target}/#{service.service_name}" if enable
  safe_system System.launchctl, "bootstrap", System.domain_target, file
end

.remove_unused_service_filesObject

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



68
69
70
71
72
73
74
75
76
77
78
79
# File 'services/cli.rb', line 68

def self.remove_unused_service_files
  cleaned = []
  Dir["#{System.path}homebrew.*.{plist,service}"].each do |file|
    next if running.include?(File.basename(file).sub(/\.(plist|service)$/i, ""))

    puts "Removing unused service file #{file}"
    rm file
    cleaned << file
  end

  cleaned
end

.run(targets, service_file = nil, verbose: false) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Run a service as defined in the formula. This does not clean the service file like start does.

Parameters:



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'services/cli.rb', line 89

def self.run(targets, service_file = nil, verbose: false)
  if service_file.present?
    file = Pathname.new service_file
    raise UsageError, "Provided service file does not exist" unless file.exist?
  end

  targets.each do |service|
    if service.pid?
      puts "Service `#{service.name}` already running, use `#{bin} restart #{service.name}` to restart."
      next
    elsif System.root?
      puts "Service `#{service.name}` cannot be run (but can be started) as root."
      next
    end

    service_load(service, file, enable: false)
  end
end

.runningArray<String>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Find all currently running services via launchctl list or systemctl list-units.

Returns:



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'services/cli.rb', line 29

def self.running
  if System.launchctl?
    Utils.popen_read(System.launchctl, "list")
  else
    System::Systemctl.popen_read("list-units",
                                 "--type=service",
                                 "--state=running",
                                 "--no-pager",
                                 "--no-legend")
  end.chomp.split("\n").filter_map do |svc|
    Regexp.last_match(0) if svc =~ /homebrew(?>\.mxcl)?\.([\w+-.@]+)/
  end
end

.service_load(service, file, enable:) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:



335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'services/cli.rb', line 335

def self.service_load(service, file, enable:)
  if System.root? && !service.service_startup?
    opoo "#{service.name} must be run as non-root to start at user login!"
  elsif !System.root? && service.service_startup?
    opoo "#{service.name} must be run as root to start at system startup!"
  end

  if System.launchctl?
    file ||= enable ? service.dest : service.service_file
    launchctl_load(service, file:, enable:)
  elsif System.systemctl?
    # Systemctl loads based upon location so only install service
    # file when it is not installed. Used with the `run` command.
    install_service_file(service, file) unless service.dest.exist?
    systemd_load(service, enable:)
  end

  function = enable ? "started" : "ran"
  ohai("Successfully #{function} `#{service.name}` (label: #{service.service_name})")
end

.start(targets, service_file = nil, verbose: false) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Start a service.

Parameters:



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'services/cli.rb', line 116

def self.start(targets, service_file = nil, verbose: false)
  file = T.let(nil, T.nilable(Pathname))

  if service_file.present?
    file = Pathname.new service_file
    raise UsageError, "Provided service file does not exist" unless file.exist?
  end

  targets.each do |service|
    if service.pid?
      puts "Service `#{service.name}` already started, use `#{bin} restart #{service.name}` to restart."
      next
    end

    odie "Formula `#{service.name}` is not installed." unless service.installed?

    file ||= if service.service_file.exist? || System.systemctl?
      nil
    elsif service.formula.opt_prefix.exist? &&
          (keg = Keg.for service.formula.opt_prefix) &&
          keg.plist_installed?
      service_file = Dir["#{keg}/*#{service.service_file.extname}"].first
      Pathname.new service_file if service_file.present?
    end

    install_service_file(service, file)

    if file.blank? && verbose
      ohai "Generated service file for #{service.formula.name}:"
      puts "   #{service.dest.read.gsub("\n", "\n   ")}"
      puts
    end

    next if take_root_ownership(service).nil? && System.root?

    service_load(service, nil, enable: true)
  end
end

.stop(targets, verbose: false, no_wait: false, max_wait: 0, keep: false) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Stop a service and unload it.

Parameters:

  • targets (Array<Services::FormulaWrapper>)
  • verbose (Boolean) (defaults to: false)
  • no_wait (Boolean) (defaults to: false)
  • max_wait (Integer, Float, nil) (defaults to: 0)
  • keep (Boolean) (defaults to: false)


165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'services/cli.rb', line 165

def self.stop(targets, verbose: false, no_wait: false, max_wait: 0, keep: false)
  targets.each do |service|
    unless service.loaded?
      rm service.dest if !keep && service.dest.exist? # get rid of installed service file anyway, dude
      if service.service_file_present?
        odie <<~EOS
          Service `#{service.name}` is started as `#{service.owner}`. Try:
            #{"sudo " unless System.root?}#{bin} stop #{service.name}
        EOS
      elsif System.launchctl? &&
            quiet_system(System.launchctl, "bootout", "#{System.domain_target}/#{service.service_name}")
        ohai "Successfully stopped `#{service.name}` (label: #{service.service_name})"
      else
        opoo "Service `#{service.name}` is not started."
      end
      next
    end

    systemctl_args = []
    if no_wait
      systemctl_args << "--no-block"
      puts "Stopping `#{service.name}`..."
    else
      puts "Stopping `#{service.name}`... (might take a while)"
    end

    if System.systemctl?
      if keep
        System::Systemctl.quiet_run(*systemctl_args, "stop", service.service_name)
      else
        System::Systemctl.quiet_run(*systemctl_args, "disable", "--now", service.service_name)
      end
    elsif System.launchctl?
      quiet_system System.launchctl, "bootout", "#{System.domain_target}/#{service.service_name}"
      unless no_wait
        time_slept = 0
        sleep_time = 1
        max_wait = T.must(max_wait)
        while ($CHILD_STATUS.to_i == 9216 || service.loaded?) && (max_wait.zero? || time_slept < max_wait)
          sleep(sleep_time)
          time_slept += sleep_time
          quiet_system System.launchctl, "bootout", "#{System.domain_target}/#{service.service_name}"
        end
      end
      quiet_system System.launchctl, "stop", "#{System.domain_target}/#{service.service_name}" if service.pid?
    end

    unless keep
      rm service.dest if service.dest.exist?
      # Run daemon-reload on systemctl to finish unloading stopped and deleted service.
      System::Systemctl.run(*systemctl_args, "daemon-reload") if System.systemctl?
    end

    if service.pid? || service.loaded?
      opoo "Unable to stop `#{service.name}` (label: #{service.service_name})"
    else
      ohai "Successfully stopped `#{service.name}` (label: #{service.service_name})"
    end
  end
end

.sudo_service_userString?

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



12
13
14
# File 'services/cli.rb', line 12

def self.sudo_service_user
  @sudo_service_user
end

.sudo_service_user=(sudo_service_user) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:



17
18
19
# File 'services/cli.rb', line 17

def self.sudo_service_user=(sudo_service_user)
  @sudo_service_user = sudo_service_user
end

.systemd_load(service, enable:) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Parameters:



329
330
331
332
# File 'services/cli.rb', line 329

def self.systemd_load(service, enable:)
  System::Systemctl.run("start", service.service_name)
  System::Systemctl.run("enable", service.service_name) if enable
end

.take_root_ownership(service) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

protections to avoid users editing root services



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'services/cli.rb', line 252

def self.take_root_ownership(service)
  return unless System.root?
  return if sudo_service_user

  root_paths = T.let([], T::Array[Pathname])

  if System.systemctl?
    group = "root"
  elsif System.launchctl?
    group = "admin"
    chown "root", group, service.dest
    plist_data = service.dest.read
    plist = begin
      Plist.parse_xml(plist_data, marshal: false)
    rescue
      nil
    end
    return unless plist

    program_location = plist["ProgramArguments"]&.first
    key = "first ProgramArguments value"
    if program_location.blank?
      program_location = plist["Program"]
      key = "Program"
    end

    if program_location.present?
      Dir.chdir("/") do
        if File.exist?(program_location)
          program_location_path = Pathname(program_location).realpath
          root_paths += [
            program_location_path,
            program_location_path.parent.realpath,
          ]
        else
          opoo <<~EOS
            #{service.name}: the #{key} does not exist:
              #{program_location}
          EOS
        end
      end
    end
  end

  if (formula = service.formula)
    root_paths += [
      formula.opt_prefix,
      formula.linked_keg,
      formula.bin,
      formula.sbin,
    ]
  end
  root_paths = root_paths.sort.uniq.select(&:exist?)

  opoo <<~EOS
    Taking root:#{group} ownership of some #{service.formula} paths:
      #{root_paths.join("\n  ")}
    This will require manual removal of these paths using `sudo rm` on
    brew upgrade/reinstall/uninstall.
  EOS
  chown "root", group, root_paths
  chmod "+t", root_paths
end