Class: Launchr::Service

Inherits:
Object
  • Object
show all
Defined in:
lib/launchr/service.rb

Defined Under Namespace

Classes: LaunchdJob

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(formula_name, jobs) ⇒ Service

Returns a new instance of Service.



326
327
328
329
330
# File 'lib/launchr/service.rb', line 326

def initialize formula_name, jobs
  @name = formula_name
  @jobs = jobs
  @keg  = keg
end

Instance Attribute Details

#jobsObject

Returns the value of attribute jobs.



323
324
325
# File 'lib/launchr/service.rb', line 323

def jobs
  @jobs
end

#nameObject

Returns the value of attribute name.



323
324
325
# File 'lib/launchr/service.rb', line 323

def name
  @name
end

#plist_statesObject

Returns the value of attribute plist_states.



324
325
326
# File 'lib/launchr/service.rb', line 324

def plist_states
  @plist_states
end

#plistsObject

Returns the value of attribute plists.



324
325
326
# File 'lib/launchr/service.rb', line 324

def plists
  @plists
end

#selected_plistsObject

Returns the value of attribute selected_plists.



324
325
326
# File 'lib/launchr/service.rb', line 324

def selected_plists
  @selected_plists
end

Class Method Details

.clean_plists_in(apple_launchdaemons) ⇒ Object



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/launchr/service.rb', line 144

def clean_plists_in apple_launchdaemons
  # scan through the homebrew LaunchDaemons folder and readlink (read the links if a symlink)
  # where the 1st level symlink points to determines the service status (up/down, running etc)
  brew_plists = Pathname.glob(Launchr::Path.homebrew_prefix+"Library/LaunchDaemons/*")
  brew_plists.map! { |p| p.readlink }

  # the services associated to these plists are installed, but should be in the down state
  # as they arent symlinked into the Apple LaunchDaemons folder
  down_brew_plists = brew_plists.select { |p| p.include? Launchr::Path.homebrew_prefix }

  # scan through the Apple LaunchDaemons folder and for all plists check their real path (final destination symlink)
  # select any plist links which point to locations in the brew tree. These should be installed and running brew services
  brew_launchdaemons_plists = apple_launchdaemons.children.select { |p| p.realpath.include? Launchr::Path.homebrew_prefix }

  # sub select (select again) any plist links which are found to be a mismatch
  # either they are not installed anymore (rm -rf'd without stopping the service)
  # and/or were resinstalled again so their service state is no longer matching
  # and reflecting the entries in the launchd database (service loaded/unloaded)
  missing_brew_launchdaemons_plists = brew_launchdaemons_plists.select do |plist|
    !plist.realpath.exist? || down_brew_plists.include?(plist.realpath)
  end

  if !missing_brew_launchdaemons_plists.empty?
    # if there are broken services at boot level, it requires root permissions
    # to fix the issue. We can detect these, and ask to re-run as root
    if !Launchr.superuser? && apple_launchdaemons == Launchr::Path.boot_launchdaemons
      puts "Launchctl database was left in an inconsistent state"
      puts "This happens when a formula is uninstalled, but the"
      puts "service was not stopped. To cleanup run the command"
      puts "`sudo brew launchd clean`"
    else
      # repair the launchctl service status and remove the symlink
      # from Apple's LaunchDaemons folder (we still keep a link in brew_launchdaemons)
      missing_brew_launchdaemons_plists.each do |plist|
        launchctl :stop, plist # ignore the return code
        plist.unlink # delete broken symlink
      end
    end
  end
end

.cleanupObject

Clean any inconcistencies between homebrew and launchctl launcd database This can happen if formula were uninstalled with ‘rm -rf’



187
188
189
190
191
# File 'lib/launchr/service.rb', line 187

def cleanup
  fix_broken_symlinks
  clean_plists_in Launchr::Path.user_launchdaemons
  clean_plists_in Launchr::Path.boot_launchdaemons
end

.find(svc) ⇒ Object

Resolve a service name to plist files, and create a new brew service object A service name can be a formula name, a formula alias, or plist filename / label



211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/launchr/service.rb', line 211

def find svc
  formula_name = nil
  jobs = []

  prefix = Launchr::Path.homebrew_prefix
  installed_plists = Pathname.glob(prefix+"Library/LaunchDaemons/*")

  case svc
  when /^[^\.]+$/
    # should be a formula name, or formula alias name

    if (prefix+"Library/Aliases/#{svc}").exist?
      # its an alias
      alias_realpath = (prefix+"Library/Aliases/#{svc}").realpath
      formula_name = alias_realpath.basename(".rb").to_s
    end

    if (prefix+"Library/Formula/#{svc}.rb").exist?
      # its a formula name
      formula_name = svc
    end

    if formula_name
      formula_plists = installed_plists.select { |p| p.realpath.include? "Cellar\/#{formula_name}" }

      jobs = formula_plists.map do |p| 
        LaunchdJob.new :plist => p, :selected => true
      end
    end

  else
    # should be a launchd job label or plist filename
    label = File.basename(svc,".plist")
    plist_link = prefix+"Library/LaunchDaemons/#{label}.plist"

    if plist_link.exist?
      formula_name = plist_link.realpath.to_s.gsub(/^.*Cellar\/|\/.*$/,"")
      formula_plists = installed_plists.select { |p| p.realpath.include? "Cellar\/#{formula_name}" }
      
      jobs = formula_plists.map do |p| 
        selected = nil
        (p == plist_link) ? selected = true : selected = false
        LaunchdJob.new :plist => p, :selected => selected
      end
      
    end
  end

  if formula_name
    Launchr::Service.new(formula_name, jobs)
  else
    # svc could be a valid service identifier, but just not installed yet. would
    # have to grep inside all the Formula files for "launchd_plist <job_label>" definitions
    # in order to figure that out. an expensive operation (but very cacheable)
    puts "Couldnt find any installed service matching \"#{svc}\" (no matches)"
    raise "Service #{svc} not found"
  end
end

.find_allObject



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/launchr/service.rb', line 193

def find_all
  prefix = Launchr::Path.homebrew_prefix
  installed_plists = Pathname.glob(prefix+"Library/LaunchDaemons/*")

  formula_names = installed_plists.map do |plist|
    plist.realpath.to_s.gsub(/^.*Cellar\/|\/.*$/,"")
  end
  formula_names.uniq!

  services = formula_names.map do |formula|
    find(formula)
  end

  services
end


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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
# File 'lib/launchr/service.rb', line 92

def fix_broken_symlinks
  brew_plists = Pathname.glob(Launchr::Path.homebrew_prefix+"Library/LaunchDaemons/*")
  broken_plists = brew_plists.select { |p| p.readable? == false }

  installed_plists_realpaths = Pathname.glob(Launchr::Path.homebrew_prefix+"Cellar/**/Library/LaunchDaemons/*.plist")

  installed_plists_realpaths.each do |real|
    pool_link = Launchr::Path.homebrew_prefix+"Library/LaunchDaemons"+real.basename
    if !pool_link.exist?
      pool_link.make_symlink(real.relative_path_from(Launchr::Path.brew_launchdaemons))
    end
  end

  if !broken_plists.empty?
    
    broken_plists.each do |broken|
      match = installed_plists_realpaths.select { |r| r.include?(broken.basename) }.first
      target = nil
      case broken.readlink
      when /Cellar/
        broken.unlink

      when /^\/Library\/LaunchDaemons/
        if !Launchr.superuser?
          puts "Launchctl database was left in an inconsistent state"
          puts "This happens when a formula is uninstalled, but the"
          puts "service was not stopped. To cleanup run the command"
          puts "`sudo brew launchd clean`"
        else
          target = Launchr::Path.boot_launchdaemons + broken.basename
          target.make_symlink(match)
          launchctl :stop, broken
          target.unlink
          broken.unlink
          if match
            broken.make_symlink(match)
          end
        end
      when /Library\/LaunchAgents/
        target = Launchr::Path.user_launchdaemons + broken.basename
        target.make_symlink(match)
        launchctl :stop, broken
        target.unlink
        broken.unlink
        if match
          broken.make_symlink(match)
        end
      end
    end
  end
end

.headerObject



475
476
477
478
479
480
# File 'lib/launchr/service.rb', line 475

def self.header
  out = []
  out << sprintf("%-20.20s %-30.30s %-10.10s %-20.20s", "Service", "Launchd job label", "Status", "Level")
  out << sprintf("%-20.20s %-30.30s %-10.10s %-20.20s", "-------", "-----------------", "------", "-----")
  out.join("\n")
end

.launchctl(action, job, sudo = nil) ⇒ Object



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
80
81
# File 'lib/launchr/service.rb', line 45

def launchctl action, job, sudo=nil
  result = nil

  case job
  when String
    job = LaunchdJob.new :plist => Pathname.new(job)
  when Pathname
    job = LaunchdJob.new :plist => job
  when LaunchdJob
  else
    raise "unrecognized argument"
  end

  args = []
  case action
  when :start, :stop, :remove
    args << job.label
  when :list
    args << "-x" << job.label
  when :load, :unload
    args << "-w" << job.plist.readlink
  when :list
    args << job.label
  else
    raise "unsupported launchctl cmd"
  end
  
  if sudo || job.level == :boot
    result = sudo_launchctl_exec action.to_s, *args
  else
    result = launchctl_exec action.to_s, *args
  end

  # puts result[:stdout] unless result[:stdout].empty?
  # puts result[:stderr] unless result[:stderr].empty?
  result
end

.launchctl_exec(*args) ⇒ Object



14
15
16
# File 'lib/launchr/service.rb', line 14

def launchctl_exec *args
  popen "/bin/launchctl", *args
end

.popen(cmd, *args) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/launchr/service.rb', line 18

def popen cmd, *args
  stdin_str = nil

  pid, stdin, stdout, stderr = ::Launchr::Popen4::popen4 [cmd, *args]

    stdin.puts stdin_str if stdin_str
    stdin.close

    ignored, status = [nil,nil]

    begin
      Timeout::timeout(Launchr.launchctl_timeout) do
        ignored, status = Process::waitpid2 pid
      end
    rescue Timeout::Error => exc
      puts "#{exc.message}, killing pid #{pid}"
      Process::kill('TERM', pid)
      # Process::kill('HUP', pid)
      ignored, status = Process::waitpid2 pid
    end

    stdout_result = stdout.read.strip
    stderr_result = stderr.read.strip

  return { :cmd => cmd, :status => status, :stdout => stdout_result, :stderr => stderr_result }
end

.sudo_launchctl(action, job) ⇒ Object



83
84
85
86
87
88
89
90
# File 'lib/launchr/service.rb', line 83

def sudo_launchctl action, job
  if Launchr.superuser?
    sudo = true
    launchctl action, job, sudo
  else
    raise "Insufficient permissions, cant sudo"
  end
end

.sudo_launchctl_exec(*args) ⇒ Object



10
11
12
# File 'lib/launchr/service.rb', line 10

def sudo_launchctl_exec *args
  popen "/usr/bin/sudo", "/bin/launchctl", *args
end

Instance Method Details

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


319
320
321
# File 'lib/launchr/service.rb', line 319

def eql? other
  @name = other.name
end

#hashObject



315
316
317
# File 'lib/launchr/service.rb', line 315

def hash
  @name.hash
end

#infoObject



516
517
518
# File 'lib/launchr/service.rb', line 516

def info
  puts printline
end

#inspectObject



512
513
514
# File 'lib/launchr/service.rb', line 512

def inspect
  self.class.header + printline
end

#kegObject



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/launchr/service.rb', line 340

def keg
  unless @keg
    @keg = false
    @jobs.each do |job|
      if job.plist && job.plist.readable?
        keg_relative = Pathname.new(job.plist.realpath.to_s.gsub(/\/Library\/LaunchDaemons.*/,""))
        @keg = keg_relative.expand_path(job.plist)
        break
      end
    end
  else
    @keg ||= false
  end
  @keg
end

#launchctl(action, job) ⇒ Object



332
333
334
# File 'lib/launchr/service.rb', line 332

def launchctl action, job
  self.class.launchctl action, job
end

#printlineObject



482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
# File 'lib/launchr/service.rb', line 482

def printline
  out = []
  jobs.each do |job|
    s = ""
    l = ""
    case job.level
    when :boot
      s << "Started"
      l << "System Boot"
    when :user
      s << "Started"
      l << "User login"
    else
      s << "Stopped"
      # l << "n/a"
      l << "-"
    end
    if job == jobs.first
      out << sprintf("%-20.20s %-30.30s %-10.10s %-20.20s", name, job.label, s, l)
    else
      out << sprintf("%-20.20s %-30.30s %-10.10s %-20.20s",   "", job.label, s, l)
    end
  end
  out.join("\n")
end

#restartObject



460
461
462
463
464
465
466
467
468
469
470
471
472
473
# File 'lib/launchr/service.rb', line 460

def restart
  if Launchr.config[:boot] && ! Launchr.superuser?
    raise "To restart a service for boot time requires sudo. Use sudo brew restart --boot #{Launchr.config[:args][:restart].join(' ')}"
  end

  selected_jobs.select { |job| job.started? }. each do |job|
    if job.level == :boot && !Launchr.superuser?
      raise "To restart a running boot time service requires sudo. Use sudo brew restart #{Launchr.config[:args][:restart].join(' ')}"
    end
  end

  stop
  start
end

#selected_jobsObject



356
357
358
# File 'lib/launchr/service.rb', line 356

def selected_jobs
  @jobs.select { |job| job.selected == true }
end

#selected_stopped_jobsObject



360
361
362
# File 'lib/launchr/service.rb', line 360

def selected_stopped_jobs
  @jobs.select { |job| job.selected == true && ! job.started? }
end

#startObject



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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/launchr/service.rb', line 364

def start
  if selected_jobs.empty?
    puts "#{name} - Nothing to start"
    return
  end

  if Launchr.config[:boot] && ! Launchr.superuser?
    raise "To start a boot time service requires sudo. Use sudo brew start --boot #{Launchr.config[:args][:start].join(' ')}"
  end

  launchdaemons = nil
  unless selected_stopped_jobs.empty?
    if Launchr.config[:boot]
      puts "Chowning #{@keg} to root:wheel"
      @keg.chown_R "root", "wheel"
      launchdaemons = Launchr::Path.boot_launchdaemons
    else
      launchdaemons = Launchr::Path.user_launchdaemons
    end
  end

  selected_jobs.each do |job|
    if Launchr.superuser? && job.level == :user
      raise "#{job.label} is already started at user login. Stop the service first, or sudo brew restart --boot"
    elsif job.level == :boot
      raise "#{job.label} is already started at boot. Stop the service first, or brew restart --user"
    end
    
    if !job.started?
      target = launchdaemons + job.plist.realpath.basename
      target.make_symlink(job.plist.realpath)

      job.plist.unlink
      job.plist.make_symlink(target)

      result = nil
      if Launchr.config[:boot]
        result = sudo_launchctl :load, job
      else
        result = launchctl :load, job
      end

      if result[:status].exitstatus != 0
        if result[:status].exitstatus
          puts "Launchctl exited with code #{result[:status].exitstatus} when trying to stop \"#{job.label}\""
        else
          puts "Launchctl terminated unexpectedly with #{result[:status].inspect}"
        end
        puts result[:stdout] unless result[:stdout].empty?
        puts result[:stderr] unless result[:stderr].empty?
      end

    end
  end
end

#stopObject



420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# File 'lib/launchr/service.rb', line 420

def stop
  if selected_jobs.empty?
    puts "#{name} - Nothing to stop"
    return
  end

  selected_jobs.each do |job|
    if job.started?
      if job.level == :boot && !Launchr.superuser?
        raise "To stop a boot time service requires sudo. Use sudo brew stop #{Launchr.config[:args][:stop].join(' ')}"
      end

      result = launchctl :unload, job

      if result[:status].exitstatus != 0
        if result[:status].exitstatus
          puts "Launchctl exited with code #{result[:status].exitstatus} when trying to stop \"#{job.label}\""
        else
          puts "Launchctl terminated unexpectedly with #{result[:status].inspect}"
        end
        puts result[:stdout] unless result[:stdout].empty?
        puts result[:stderr] unless result[:stderr].empty?
      end

      source = job.plist.realpath
      job.plist.readlink.unlink
      job.plist.unlink
      job.plist.make_symlink(source.relative_path_from(Launchr::Path.brew_launchdaemons))
      
    end
  end

  if Launchr.superuser? && @jobs.select { |job| job.level == :boot }.empty?
    if @keg.user == "root"
      puts "Chowning #{@keg} to #{@keg.parent.user}:#{@keg.parent.group}"
      @keg.chown_R @keg.parent.user, @keg.parent.group
    end
  end
end

#sudo_launchctl(action, job) ⇒ Object



336
337
338
# File 'lib/launchr/service.rb', line 336

def sudo_launchctl action, job
  self.class.sudo_launchctl action, job
end

#to_sObject



508
509
510
# File 'lib/launchr/service.rb', line 508

def to_s
  name
end