Class: Homebrew::Service

Inherits:
Object show all
Extended by:
Forwardable
Includes:
OnSystem::MacOSAndLinux
Defined in:
service.rb

Overview

The Service class implements the DSL methods used in a formula’s service block and stores related instance variables. Most of these methods also return the related instance variable when no argument is provided.

Constant Summary collapse

RUN_TYPE_IMMEDIATE =
:immediate
RUN_TYPE_INTERVAL =
:interval
RUN_TYPE_CRON =
:cron
PROCESS_TYPE_BACKGROUND =
:background
PROCESS_TYPE_STANDARD =
:standard
PROCESS_TYPE_INTERACTIVE =
:interactive
PROCESS_TYPE_ADAPTIVE =
:adaptive
KEEP_ALIVE_KEYS =
[:always, :successful_exit, :crashed, :path].freeze

Class Method Summary collapse

Instance Method Summary collapse

Methods included from OnSystem::MacOSAndLinux

included

Constructor Details

#initialize(formula, &block) ⇒ Service

sig { params(formula: Formula).void }



26
27
28
29
30
31
32
# File 'service.rb', line 26

def initialize(formula, &block)
  @formula = formula
  @run_type = RUN_TYPE_IMMEDIATE
  @run_at_load = true
  @environment_variables = {}
  instance_eval(&block) if block
end

Class Method Details

.deserialize(api_hash) ⇒ Hash

Turn the service API hash values back into what is expected by the formula DSL.

Parameters:

  • api_hash (Hash)

Returns:

  • (Hash)


575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
# File 'service.rb', line 575

def self.deserialize(api_hash)
  hash = {}
  hash[:name] = api_hash["name"].transform_keys(&:to_sym) if api_hash.key?("name")

  # The service hash might not have a "run" command if it only documents
  # an existing service file with the "name" command.
  return hash unless api_hash.key?("run")

  hash[:run] =
    case api_hash["run"]
    when String
      replace_placeholders(api_hash["run"])
    when Array
      api_hash["run"].map(&method(:replace_placeholders))
    when Hash
      api_hash["run"].to_h do |key, elem|
        run_cmd = if elem.is_a?(Array)
          elem.map(&method(:replace_placeholders))
        else
          replace_placeholders(elem)
        end

        [key.to_sym, run_cmd]
      end
    else
      raise ArgumentError, "Unexpected run command: #{api_hash["run"]}"
    end

  hash[:keep_alive] = api_hash["keep_alive"].transform_keys(&:to_sym) if api_hash.key?("keep_alive")

  if api_hash.key?("environment_variables")
    hash[:environment_variables] = api_hash["environment_variables"].to_h do |key, value|
      [key.to_sym, replace_placeholders(value)]
    end
  end

  %w[run_type process_type].each do |key|
    next unless (value = api_hash[key])

    hash[key.to_sym] = value.to_sym
  end

  %w[working_dir root_dir input_path log_path error_log_path].each do |key|
    next unless (value = api_hash[key])

    hash[key.to_sym] = replace_placeholders(value)
  end

  %w[interval cron launch_only_once require_root restart_delay macos_legacy_timers sockets].each do |key|
    next if (value = api_hash[key]).nil?

    hash[key.to_sym] = value
  end

  hash
end

.replace_placeholders(string) ⇒ String

Replace API path placeholders with local paths.

Parameters:

Returns:



634
635
636
637
# File 'service.rb', line 634

def self.replace_placeholders(string)
  string.gsub(HOMEBREW_PREFIX_PLACEHOLDER, HOMEBREW_PREFIX)
        .gsub(HOMEBREW_HOME_PLACEHOLDER, Dir.home)
end

Instance Method Details

#commandArray<String>?

Returns:



385
386
387
# File 'service.rb', line 385

def command
  @run&.map(&:to_s)&.map { |arg| arg.start_with?("~") ? File.expand_path(arg) : arg }
end

#command?Boolean

Returns:

  • (Boolean)


390
391
392
# File 'service.rb', line 390

def command?
  @run.present?
end

#cron(value = nil) ⇒ Hash?

Parameters:

  • value (String, nil) (defaults to: nil)

Returns:

  • (Hash, nil)


298
299
300
301
302
303
304
305
306
307
# File 'service.rb', line 298

def cron(value = nil)
  case T.unsafe(value)
  when nil
    @cron
  when String
    @cron = parse_cron(T.must(value))
  else
    raise TypeError, "Service#cron expects a String"
  end
end

#default_cron_valuesHash{Symbol => Integer, String}

Returns:



310
311
312
313
314
315
316
317
318
# File 'service.rb', line 310

def default_cron_values
  {
    Month:   "*",
    Day:     "*",
    Weekday: "*",
    Hour:    "*",
    Minute:  "*",
  }
end

#default_plist_nameString

Returns:



40
41
42
# File 'service.rb', line 40

def default_plist_name
  "homebrew.mxcl.#{@formula.name}"
end

#default_service_nameString

Returns:



50
51
52
# File 'service.rb', line 50

def default_service_name
  "homebrew.#{@formula.name}"
end

#environment_variables(variables = {}) ⇒ Hash{Symbol => String}?

Parameters:

Returns:



356
357
358
359
360
361
362
363
# File 'service.rb', line 356

def environment_variables(variables = {})
  case T.unsafe(variables)
  when Hash
    @environment_variables = variables.transform_values(&:to_s)
  else
    raise TypeError, "Service#environment_variables expects a hash"
  end
end

#error_log_path(path = nil) ⇒ String?

Parameters:

Returns:



144
145
146
147
148
149
150
151
152
153
# File 'service.rb', line 144

def error_log_path(path = nil)
  case T.unsafe(path)
  when nil
    @error_log_path
  when String, Pathname
    @error_log_path = path.to_s
  else
    raise TypeError, "Service#error_log_path expects a String"
  end
end

#fFormula

Returns:



35
36
37
# File 'service.rb', line 35

def f
  @formula
end

#input_path(path = nil) ⇒ String?

Parameters:

Returns:



120
121
122
123
124
125
126
127
128
129
# File 'service.rb', line 120

def input_path(path = nil)
  case T.unsafe(path)
  when nil
    @input_path
  when String, Pathname
    @input_path = path.to_s
  else
    raise TypeError, "Service#input_path expects a String or Pathname"
  end
end

#interval(value = nil) ⇒ Integer?

Parameters:

  • value (Integer, nil) (defaults to: nil)

Returns:

  • (Integer, nil)


286
287
288
289
290
291
292
293
294
295
# File 'service.rb', line 286

def interval(value = nil)
  case T.unsafe(value)
  when nil
    @interval
  when Integer
    @interval = value
  else
    raise TypeError, "Service#interval expects an Integer"
  end
end

#keep_alive(value = nil) ⇒ Hash{Symbol => T.untyped}?

Parameters:

  • value (Boolean, Hash{Symbol => T.untyped}, nil) (defaults to: nil)

Returns:

  • (Hash{Symbol => T.untyped}, nil)


159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'service.rb', line 159

def keep_alive(value = nil)
  case T.unsafe(value)
  when nil
    @keep_alive
  when true, false
    @keep_alive = { always: value }
  when Hash
    hash = T.cast(value, Hash)
    unless (hash.keys - KEEP_ALIVE_KEYS).empty?
      raise TypeError, "Service#keep_alive allows only #{KEEP_ALIVE_KEYS}"
    end

    @keep_alive = value
  else
    raise TypeError, "Service#keep_alive expects a Boolean or Hash"
  end
end

#keep_alive?Boolean

Returns a Boolean describing if a service is set to be kept alive.

Returns:

  • (Boolean)


227
228
229
# File 'service.rb', line 227

def keep_alive?
  @keep_alive.present? && @keep_alive[:always] != false
end

#launch_only_once(value = nil) ⇒ Boolean?

Parameters:

  • value (Boolean, nil) (defaults to: nil)

Returns:

  • (Boolean, nil)


232
233
234
235
236
237
238
239
240
241
# File 'service.rb', line 232

def launch_only_once(value = nil)
  case T.unsafe(value)
  when nil
    @launch_only_once
  when true, false
    @launch_only_once = value
  else
    raise TypeError, "Service#launch_only_once expects a Boolean"
  end
end

#log_path(path = nil) ⇒ String?

Parameters:

Returns:



132
133
134
135
136
137
138
139
140
141
# File 'service.rb', line 132

def log_path(path = nil)
  case T.unsafe(path)
  when nil
    @log_path
  when String, Pathname
    @log_path = path.to_s
  else
    raise TypeError, "Service#log_path expects a String"
  end
end

#macos_legacy_timers(value = nil) ⇒ Boolean?

Parameters:

  • value (Boolean, nil) (defaults to: nil)

Returns:

  • (Boolean, nil)


366
367
368
369
370
371
372
373
374
375
# File 'service.rb', line 366

def macos_legacy_timers(value = nil)
  case T.unsafe(value)
  when nil
    @macos_legacy_timers
  when true, false
    @macos_legacy_timers = value
  else
    raise TypeError, "Service#macos_legacy_timers expects a Boolean"
  end
end

#manual_commandString

Returns the String command to run manually instead of the service.

Returns:



397
398
399
400
401
402
403
# File 'service.rb', line 397

def manual_command
  vars = @environment_variables.except(:PATH)
                               .map { |k, v| "#{k}=\"#{v}\"" }

  out = vars + command if command?
  out.join(" ")
end

#name(macos: nil, linux: nil) ⇒ void

This method returns an undefined value.

Parameters:

  • macos (String, nil) (defaults to: nil)
  • linux (String, nil) (defaults to: nil)

Raises:

  • (TypeError)


60
61
62
63
64
65
# File 'service.rb', line 60

def name(macos: nil, linux: nil)
  raise TypeError, "Service#name expects at least one String" if [macos, linux].none?(String)

  @plist_name = macos if macos
  @service_name = linux if linux
end

#parse_cron(cron_statement) ⇒ Hash{Symbol => Integer, String}

Parameters:

Returns:



321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'service.rb', line 321

def parse_cron(cron_statement)
  parsed = default_cron_values

  case cron_statement
  when "@hourly"
    parsed[:Minute] = 0
  when "@daily"
    parsed[:Minute] = 0
    parsed[:Hour] = 0
  when "@weekly"
    parsed[:Minute] = 0
    parsed[:Hour] = 0
    parsed[:Weekday] = 0
  when "@monthly"
    parsed[:Minute] = 0
    parsed[:Hour] = 0
    parsed[:Day] = 1
  when "@yearly", "@annually"
    parsed[:Minute] = 0
    parsed[:Hour] = 0
    parsed[:Day] = 1
    parsed[:Month] = 1
  else
    cron_parts = cron_statement.split
    raise TypeError, "Service#parse_cron expects a valid cron syntax" if cron_parts.length != 5

    [:Minute, :Hour, :Day, :Month, :Weekday].each_with_index do |selector, index|
      parsed[selector] = Integer(cron_parts.fetch(index)) if cron_parts.fetch(index) != "*"
    end
  end

  parsed
end

#plist_nameString

Returns:



45
46
47
# File 'service.rb', line 45

def plist_name
  @plist_name ||= default_plist_name
end

#process_type(value = nil) ⇒ Symbol?

Parameters:

  • value (Symbol, nil) (defaults to: nil)

Returns:



256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'service.rb', line 256

def process_type(value = nil)
  case T.unsafe(value)
  when nil
    @process_type
  when :background, :standard, :interactive, :adaptive
    @process_type = value
  when Symbol
    raise TypeError, "Service#process_type allows: " \
                     "'#{PROCESS_TYPE_BACKGROUND}'/'#{PROCESS_TYPE_STANDARD}'/" \
                     "'#{PROCESS_TYPE_INTERACTIVE}'/'#{PROCESS_TYPE_ADAPTIVE}'"
  else
    raise TypeError, "Service#process_type expects a Symbol"
  end
end

#require_root(value = nil) ⇒ Boolean?

Parameters:

  • value (Boolean, nil) (defaults to: nil)

Returns:

  • (Boolean, nil)


178
179
180
181
182
183
184
185
186
187
# File 'service.rb', line 178

def require_root(value = nil)
  case T.unsafe(value)
  when nil
    @require_root
  when true, false
    @require_root = value
  else
    raise TypeError, "Service#require_root expects a Boolean"
  end
end

#requires_root?Boolean

Returns a Boolean describing if a service requires root access.

Returns:

  • (Boolean)


192
193
194
# File 'service.rb', line 192

def requires_root?
  @require_root.present? && @require_root == true
end

#restart_delay(value = nil) ⇒ Integer?

Parameters:

  • value (Integer, nil) (defaults to: nil)

Returns:

  • (Integer, nil)


244
245
246
247
248
249
250
251
252
253
# File 'service.rb', line 244

def restart_delay(value = nil)
  case T.unsafe(value)
  when nil
    @restart_delay
  when Integer
    @restart_delay = value
  else
    raise TypeError, "Service#restart_delay expects an Integer"
  end
end

#root_dir(path = nil) ⇒ String?

Parameters:

Returns:



108
109
110
111
112
113
114
115
116
117
# File 'service.rb', line 108

def root_dir(path = nil)
  case T.unsafe(path)
  when nil
    @root_dir
  when String, Pathname
    @root_dir = path.to_s
  else
    raise TypeError, "Service#root_dir expects a String or Pathname"
  end
end

#run(command = nil, macos: nil, linux: nil) ⇒ Array?

Parameters:

Returns:



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'service.rb', line 74

def run(command = nil, macos: nil, linux: nil)
  # Save parameters for serialization
  if command
    @run_params = command
  elsif macos || linux
    @run_params = { macos: macos, linux: linux }.compact
  end

  command ||= on_system_conditional(macos: macos, linux: linux)
  case T.unsafe(command)
  when nil
    @run
  when String, Pathname
    @run = [command]
  when Array
    @run = command
  else
    raise TypeError, "Service#run expects an Array"
  end
end

#run_at_load(value = nil) ⇒ Boolean?

Parameters:

  • value (Boolean, nil) (defaults to: nil)

Returns:

  • (Boolean, nil)


197
198
199
200
201
202
203
204
205
206
# File 'service.rb', line 197

def run_at_load(value = nil)
  case T.unsafe(value)
  when nil
    @run_at_load
  when true, false
    @run_at_load = value
  else
    raise TypeError, "Service#run_at_load expects a Boolean"
  end
end

#run_type(value = nil) ⇒ Symbol?

Parameters:

  • value (Symbol, nil) (defaults to: nil)

Returns:



272
273
274
275
276
277
278
279
280
281
282
283
# File 'service.rb', line 272

def run_type(value = nil)
  case T.unsafe(value)
  when nil
    @run_type
  when :immediate, :interval, :cron
    @run_type = value
  when Symbol
    raise TypeError, "Service#run_type allows: '#{RUN_TYPE_IMMEDIATE}'/'#{RUN_TYPE_INTERVAL}'/'#{RUN_TYPE_CRON}'"
  else
    raise TypeError, "Service#run_type expects a Symbol"
  end
end

#serializeHash

Prepare the service hash for inclusion in the formula API JSON.

Returns:

  • (Hash)


535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
# File 'service.rb', line 535

def serialize
  name_params = {
    macos: (plist_name if plist_name != default_plist_name),
    linux: (service_name if service_name != default_service_name),
  }.compact

  return { name: name_params }.compact_blank if @run_params.blank?

  cron_string = if @cron.present?
    [:Minute, :Hour, :Day, :Month, :Weekday]
      .map { |key| @cron[key].to_s }
      .join(" ")
  end

  sockets_string = "#{@sockets[:type]}://#{@sockets[:host]}:#{@sockets[:port]}" if @sockets.present?

  {
    name:                  name_params.presence,
    run:                   @run_params,
    run_type:              @run_type,
    interval:              @interval,
    cron:                  cron_string,
    keep_alive:            @keep_alive,
    launch_only_once:      @launch_only_once,
    require_root:          @require_root,
    environment_variables: @environment_variables.presence,
    working_dir:           @working_dir,
    root_dir:              @root_dir,
    input_path:            @input_path,
    log_path:              @log_path,
    error_log_path:        @error_log_path,
    restart_delay:         @restart_delay,
    process_type:          @process_type,
    macos_legacy_timers:   @macos_legacy_timers,
    sockets:               sockets_string,
  }.compact
end

#service_nameString

Returns:



55
56
57
# File 'service.rb', line 55

def service_name
  @service_name ||= default_service_name
end

#sockets(value = nil) ⇒ Hash{Symbol => String}?

Parameters:

  • value (String, nil) (defaults to: nil)

Returns:



209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'service.rb', line 209

def sockets(value = nil)
  case T.unsafe(value)
  when nil
    @sockets
  when String
    match = T.must(value).match(%r{([a-z]+)://([a-z0-9.]+):([0-9]+)}i)
    raise TypeError, "Service#sockets a formatted socket definition as <type>://<host>:<port>" if match.blank?

    type, host, port = match.captures
    @sockets = { host: host, port: port, type: type }
  else
    raise TypeError, "Service#sockets expects a String"
  end
end

#std_service_path_envString

Returns:



380
381
382
# File 'service.rb', line 380

def std_service_path_env
  "#{HOMEBREW_PREFIX}/bin:#{HOMEBREW_PREFIX}/sbin:/usr/bin:/bin:/usr/sbin:/sbin"
end

#timed?Boolean

Returns a Boolean describing if a service is timed.

Returns:

  • (Boolean)


408
409
410
# File 'service.rb', line 408

def timed?
  @run_type == RUN_TYPE_CRON || @run_type == RUN_TYPE_INTERVAL
end

#to_plistString

Returns a String plist.

Returns:



415
416
417
418
419
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
459
460
461
462
463
464
465
466
467
468
469
470
# File 'service.rb', line 415

def to_plist
  # command needs to be first because it initializes all other values
  base = {
    Label:            plist_name,
    ProgramArguments: command,
    RunAtLoad:        @run_at_load == true,
  }

  base[:LaunchOnlyOnce] = @launch_only_once if @launch_only_once == true
  base[:LegacyTimers] = @macos_legacy_timers if @macos_legacy_timers == true
  base[:TimeOut] = @restart_delay if @restart_delay.present?
  base[:ProcessType] = @process_type.to_s.capitalize if @process_type.present?
  base[:StartInterval] = @interval if @interval.present? && @run_type == RUN_TYPE_INTERVAL
  base[:WorkingDirectory] = File.expand_path(@working_dir) if @working_dir.present?
  base[:RootDirectory] = File.expand_path(@root_dir) if @root_dir.present?
  base[:StandardInPath] = File.expand_path(@input_path) if @input_path.present?
  base[:StandardOutPath] = File.expand_path(@log_path) if @log_path.present?
  base[:StandardErrorPath] = File.expand_path(@error_log_path) if @error_log_path.present?
  base[:EnvironmentVariables] = @environment_variables unless @environment_variables.empty?

  if keep_alive?
    if (always = @keep_alive[:always].presence)
      base[:KeepAlive] = always
    elsif @keep_alive.key?(:successful_exit)
      base[:KeepAlive] = { SuccessfulExit: @keep_alive[:successful_exit] }
    elsif @keep_alive.key?(:crashed)
      base[:KeepAlive] = { Crashed: @keep_alive[:crashed] }
    elsif @keep_alive.key?(:path) && @keep_alive[:path].present?
      base[:KeepAlive] = { PathState: @keep_alive[:path].to_s }
    end
  end

  if @sockets.present?
    base[:Sockets] = {}
    base[:Sockets][:Listeners] = {
      SockNodeName:    @sockets[:host],
      SockServiceName: @sockets[:port],
      SockProtocol:    @sockets[:type].upcase,
      SockFamily:      "IPv4v6",
    }
  end

  if @cron.present? && @run_type == RUN_TYPE_CRON
    base[:StartCalendarInterval] = @cron.reject { |_, value| value == "*" }
  end

  # Adding all session types has as the primary effect that if you initialise it through e.g. a Background session
  # and you later "physically" sign in to the owning account (Aqua session), things shouldn't flip out.
  # Also, we're not checking @process_type here because that is used to indicate process priority and not
  # necessarily if it should run in a specific session type. Like database services could run with ProcessType
  # Interactive so they have no resource limitations enforced upon them, but they aren't really interactive in the
  # general sense.
  base[:LimitLoadToSessionType] = %w[Aqua Background LoginWindow StandardIO System]

  base.to_plist
end

#to_systemd_timerString

Returns a String systemd unit timer.

Returns:



508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
# File 'service.rb', line 508

def to_systemd_timer
  timer = <<~EOS
    [Unit]
    Description=Homebrew generated timer for #{@formula.name}

    [Install]
    WantedBy=timers.target

    [Timer]
    Unit=#{service_name}
  EOS

  options = []
  options << "Persistent=true" if @run_type == RUN_TYPE_CRON
  options << "OnUnitActiveSec=#{@interval}" if @run_type == RUN_TYPE_INTERVAL

  if @run_type == RUN_TYPE_CRON
    minutes = (@cron[:Minute] == "*") ? "*" : format("%02d", @cron[:Minute])
    hours   = (@cron[:Hour] == "*") ? "*" : format("%02d", @cron[:Hour])
    options << "OnCalendar=#{@cron[:Weekday]}-*-#{@cron[:Month]}-#{@cron[:Day]} #{hours}:#{minutes}:00"
  end

  timer + options.join("\n")
end

#to_systemd_unitString

Returns a String systemd unit.

Returns:



475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
# File 'service.rb', line 475

def to_systemd_unit
  unit = <<~EOS
    [Unit]
    Description=Homebrew generated unit for #{@formula.name}

    [Install]
    WantedBy=default.target

    [Service]
  EOS

  # command needs to be first because it initializes all other values
  cmd = command&.join(" ")

  options = []
  options << "Type=#{(@launch_only_once == true) ? "oneshot" : "simple"}"
  options << "ExecStart=#{cmd}"

  options << "Restart=always" if @keep_alive.present? && @keep_alive[:always].present?
  options << "RestartSec=#{restart_delay}" if @restart_delay.present?
  options << "WorkingDirectory=#{File.expand_path(@working_dir)}" if @working_dir.present?
  options << "RootDirectory=#{File.expand_path(@root_dir)}" if @root_dir.present?
  options << "StandardInput=file:#{File.expand_path(@input_path)}" if @input_path.present?
  options << "StandardOutput=append:#{File.expand_path(@log_path)}" if @log_path.present?
  options << "StandardError=append:#{File.expand_path(@error_log_path)}" if @error_log_path.present?
  options += @environment_variables.map { |k, v| "Environment=\"#{k}=#{v}\"" } if @environment_variables.present?

  unit + options.join("\n")
end

#working_dir(path = nil) ⇒ String?

Parameters:

Returns:



96
97
98
99
100
101
102
103
104
105
# File 'service.rb', line 96

def working_dir(path = nil)
  case T.unsafe(path)
  when nil
    @working_dir
  when String, Pathname
    @working_dir = path.to_s
  else
    raise TypeError, "Service#working_dir expects a String"
  end
end